date
int64
1,220B
1,719B
question_description
stringlengths
28
29.9k
accepted_answer
stringlengths
12
26.4k
question_title
stringlengths
14
159
1,430,404,323,000
I wrote this shell script which sort of confused me a bit... function func { the variables received are echo $0: $1 and $2 } echo in the main script func ball boy The name of script is shell.txt I expected the result to be func : ball and boy However I got ./shell.txt :ball and boy I have read that the positional ...
In bash some variables are reserved, such as $0 which gives the command name -- in this instance it is the name of the script (hence ./shell.txt). Another example is $$ which will give the process ID. I believe that $FUNCNAME should print the name of the function being used. Any variables in the format $1 $2 $3 etc wi...
Nature of the positional parameters
1,430,404,323,000
I wrote the following bash function: function to_company() { scp ${1} [email protected]://home/username } When I do: $ to_company code_diff.txt It asks for password and then fails with following message: scp: //home/username: not a regular file I tried giving //home/username/ & //home/username/${1} in t...
Not that it should matter, but the remote path should be /home/username (single forward slash). And as sputnick pointed out, quote your ${1} with "${1}". I've copied the same command and it works when I test it, so I suspect (given the "not a regular file" error) that you have an extra space between [email protected]:...
Bash function to scp a file not working
1,430,404,323,000
I want to find the last index of any character in the [abc] set in the abcabc string but the search should start from the end of the string: " Returns the 0th index but I want the 5th. let a=match('abcabc', '[abc]') I skimmed through Vim's "4. Builtin Functions" (:h functions) but the only method that looked promisi...
I looked around, but did not find any built in function that looked like it would do what you want. You might find the following functions useful though: (variations included for overlapping, and non-overlapping matches starting from the beginning or the end of the string; all of them support multi-character patterns ...
How to reverse-match a string in the Vim programming language?
1,430,404,323,000
Like HERE I have a file.csv with numbers in quotes: "0.2" "0.3339" "0.111111" To round the number (3 decimals) this solutions works great: printf "%.03f\n" $(sed 's/\"//g' file.csv) But now I want to store sed 's/\"//g' file.csv as a variable var_sed=$(sed 's/\"//g' file.csv); printf "%.03f\n" ${var_sed} Doesn't wo...
printf "%.03f\n" $(sed 's/\"//g' file.csv) var_sed=$(sed 's/\"//g' file.csv); printf "%.03f\n" ${var_sed} This relies on word splitting to give the numbers to printf as separate arguments. The thing is, that zsh has dropped automatic word splitting as a silly remnant of the past, and doesn't do it for variable exp...
printf "%.3f" ${variable with newlines} - error with \n
1,430,404,323,000
I have this function: cyan=`tput setaf 6` reset=`tput sgr0` function Info() { echo "${cyan}$1${reset}" } And I use it in my other scripts as simple as Info some message. However, when I use it to print all items of an array, it only prints the first item: Info "${ArrayVariable[@]}" # this only prints the first it...
In your function, $1 expands to the first argument. When you call your function using Info some message ... then the value of $1 is some, while the value of $2 is message. You can keep your function as it is and instead call it with Info 'some message' or Info "$mymessage" or Info "${mymessagearray[*]}" Quoting t...
How to preserve parameter expansion passed to a function?
1,430,404,323,000
I have a directory with files file1.c, file2.c and file3.c. The command find outputs: $find -name "*.c" ./file1.c ./file2.c ./file3.c Then I would like to use find without the quotes around .*c. For this I use set -f: $echo $- # check current options himBHs $set -f $echo $- # check that f ...
You didn't say, but you must be calling the function like this: find -name *.c But globbing hasn't been turned off yet, so the shell expands the *.c before the call. So the find command sees '-name' followed by three arguments, thus the error message. You could use a backslash instead of quotes. find -name \*.c
set -f inside function
1,430,404,323,000
The other question asks about the limit on building up commands by find's -exec ... {} +. Here I'd like to know how those limits compare to shells' inner limits. Do they mimic system limits or are they independent? What are they? I'm a Bash user, but will learn of any Unix and Linux shells if only out of curiosity.
Does the system-wide limit on argument count apply in shell functions? No, that's a limit on the execve() system call used by processes to execute a different executable to replace the current one. That does not apply to functions which are interpreted by the current shell interpreter in the same process. That also ...
Does the system-wide limit on argument count apply in shell functions?
1,430,404,323,000
So I'm creating a function that does a for loop in all the files in a directory as a given argument and prints out all the files and directories: #!/bin/bash List () { for item in $1 do echo "$item" done } List ~/* However when I run the script it only prints out the first fi...
If you're trying to iterate over files in a directory you need to glob the directory like so: #!/bin/bash List () { for item in "${1}/"* do echo "$item" done } Then call it like: $ list ~ Alternatively, if you want to pass multiple files as arguments you can write your for loop like ...
For loop not working in a function with arguments
1,430,404,323,000
In bash, there is a shell builtin command named caller whose function is described as follows by the help command: Return the context of the current subroutine call But, what is a context of a subroutine call? Could you explain this to non-programmers and what it is good for knowing it?
Taken directly from the bash man page: caller ... displays the line number and source filename of the current subroutine call. In simple terms, it tells you where you just came from. Think of it like the fairy take where two kids are exploring the woods and leaving breadcrumbs along the path they take. The caller bu...
what is a context of a subroutine?
1,430,404,323,000
I have gotten quite prolific with the use of the aliases, especially with all the different git commands and their order and interdependencies etc. So, I've created a few alias that run more complex scripts. alias stash='f() { .... }; f' Over all very straight forward. However, as a bit of a purest in my developmen...
You could source into your environment a list of needed functions. Create a file ~/.bash_functions and source it from ~./bashrc. The same way as ./bash_aliases is sourced: if [ -f ~/.bash_functions ]; then . ~/.bash_functions fi Then, define as many (and as complex) functions you wish. You could define aliases (i...
Bash (Git) - Functions, Alias, and SH script files
1,430,404,323,000
vishex () { echo '#!/bin/bash' > $1; chmod +x $1; vi $1 } The goal of the above function is to have an alias for fast and comfortable creation of bash scripts. I would like that at the opening of the file the cursor would be not standing in the Shebang line but on a line below. I've tried something like ...
Use this: vishex () { [ -e "$1" ] || echo -e '#!/bin/bash\n\n' > "$1"; chmod +x "$1"; vi "+normal G" +startinsert "$1" } [ -e "$1" ] checks if the script already exists. If yes echo will not override it. -e in echo enables interpretation of backslash escapes, such as \n for a newline. Then it inserts ...
Cursor position in vi at opening of the file
1,430,404,323,000
I've couple instances of script.sh running in parallel, doing the same thing, running in background. I'm trying to use a function to kill all the current running scripts when executed. So, for example, ./script.sh -start will start the script (which I can run few in parallel) and when I execute ./script.sh -kill will ...
The script may be killing itself. You might try running the for loop inside a separate subshell ( for i in $pidsToKill; do kill -9 $i; done; echo All dead. ) & and then exit your script.
Killing multiple instances of the script from the script itself
1,430,404,323,000
I have a script I made for work that will call a function that takes an argument. I use the arguments to ssh into our servers. My question is: Is there a way to call the method so that if/when I get disconnected from our servers, It will automatically call the script? So for example, I can ssh into one of our servers....
You'll need to loop infinitely, but prevent the script from running again when you are done. while ((1)); do script.sh; sleep 3; done The three second sleep gives you an opportunity to break the loop. When you're done with ssh, exit. In three seconds, the script will start again. If you don't want that to happen, ...
Call the script after disconnecting from server
1,430,404,323,000
I want to generate a set of functions in my shell in a for loop, but I can't see how to access a variable inside the function body of the function I'm creating. In essence, I would like the following for f in foo ; do $f() { echo $f } ; done to generate a function foo() { echo foo }, but instead I get foo() { echo $f...
That's typically a case where you need eval. $ for f (foo) eval "\$f() echo ${(qq)f}" $ which foo foo () { echo 'foo' }
Expand variable in function definition in zsh
1,430,404,323,000
mv or cp commands both expect source and destination as arguments. In case you want to undo the change you made, or just change the source and destination you supplied before, what is the quickest way to do this? I thought of creating a function that takes command src dest and switching src and dest, but I was wonderi...
Not a way using cp and mv, but using a feature of GNU bash with readline with the usual (emacs-like) keybindings: Just like in emacs, you can transpose words with M-t (meta-, alt-), so if you're using bash, undoing mv file_a file_b could be as simple as pressing the up arrow and hitting M-t, which changes the above to...
Switching source and destination (or undoing the mv, cp operation)
1,430,404,323,000
I am trying to make the zsh prompt reload a function everytime a new prompt loads. The function outputs a version of pwd but shorter, if the output of pwd was ~/Downloads/Folder the function would output ~/D/Folder. The function works but does not reload if I change directories. This is an issue with zsh and not with ...
You set the content of the prompt once and for all when .zshrc is processed. There is nothing in your code that says to change the content of the prompt when the current directory changes. One solution is to put the code to change the prompt in a chpwd hook. Remove setopt prompt_subst since you won't be doing any eval...
zsh does not reload functions in the prompt
1,430,404,323,000
I make a lot of presentations that involve many screenshots, and I want an easier way to organize them by project. I'm trying to write a simple function that changes the location where screenshots are saved to the current working directory. I've written a function in and saved it to ~/.my_custom_commands.sh. That fil...
This slightly different syntax appears to work for me; it's probably that . isn't correctly handled by the service MacOS has running in the background: ~/foo $ defaults write com.apple.screencapture location "$(pwd)" ~/foo $ defaults read com.apple.screencapture { "last-messagetrace-stamp" = "576625649.15493"; ...
MacOS: Changing screen capture location
1,430,404,323,000
Consider this function: function add_one(in_ar, each) { for (each in in_ar) { in_ar[each]++ } } I would like to modify it such that if a second array is provided, it would be used instead of modifying the input array. I tried this: function add_one(in_ar, out_ar, each) { if (out_ar) { for (each in i...
There are 2 problems in your script the variable z isn't initialized the test if(out_ar) in your second code snippet is not suited for arrays To solve the first problem, you need to assign an array element (like z[1]=1) since there is no array declaration in awk. (You can't use similar statement like declare -A as...
Detect optional function argument (array)
1,430,404,323,000
Trying to run: function which_terminal { return (ps -p$PPID | awk "'NR==2'" | cut -d "' '" -f 11) } inside .zshrc to get a varible with which terminal emulator is running so I can configure different themes for different terminal emulators. when I run this commmand in command line I get exactly the emulator b...
In the shell, the return value of a function is like the exit status of a command: you can only return a small integer value indicating success (0) or a failure code (> 0). This status has nothing to do with the output of a command. To run a command and store its output into a variable, use command substitution. To ru...
Command don't return expected value inside .zshrc
1,430,404,323,000
I have the following code in my ~/.zshrc: nv() ( if vim --serverlist | grep -q VIM; then if [[ $# -eq 0 ]]; then vim elif [[ $1 == -b ]]; then shift 1 IFS=' ' vim --remote "$@" vim --remote-send ":argdo setl binary ft=xxd<cr>" vim --remote-send ":argdo %!xxd<cr><cr>" e...
The problem is starting a background job from a trap. The job seems to get “lost” sometimes. Changing vim to vim & makes the job be retained sometimes, so there may be a race condition. You could avoid this by not starting the job from a trap. Set a flag in the trap, and fire up vim outside the trap, in the precmd hoo...
How to start Vim from a trap and still be able to resume it after suspending it?
1,430,404,323,000
This is what I want to achieve: Function: Func1() { $1="Hello World" } Call function: local var1 Func1 var1 echo $var1 (should echo Hello World) I found this example which seems to work, but I guess using eval is not a good idea: Func1() { eval $1=$str1 } How would be the correct way of doing this? I'm comin...
eval is fine if you use it properly: Func1() { eval "$1=\$str1" } Is safe as long as Func1 is only called with the variable names you intend it to be passed. As always, you need to quote your variables. And here, $str1 doesn't need to be expanded before being passed to eval. If Func1 may be passed arbitrary strings...
Save return value from a function in one of its own parameters
1,430,404,323,000
I'm trying to create a bash alias alias backlight='__backlight () { echo "$@"; cd ~/Code/MSI-Backlight; sudo nodejs ~/Code/MSI-Backlight/msi-backlight.js "$@"; }', it works fine with no parameters but breaks when I give it one. It works fine outside of an alias. Does anyone know what's wrong?
You should define it as a function and call it with the alias: function __blacklight() { echo "$@"; cd ~/Code/MSI-Backlight; sudo nodejs ~/Code/MSI-Backlight/msi-backlight.js "$@"; } alias backlight='__blacklight'
bash: syntax error near unexpected token
1,430,404,323,000
I tested this: ~$ test() { echo foo |sed -r s/.*(.)/\\1/g; } ~$ test o So far so good. But then: ~$ export -f test ~$ bash -c '' bash: test: line 0: syntax error near unexpected token `(' bash: test: line 0: `test () { echo foo | sed -r s/.*(.)/\\1/g' bash: error importing function definition for `test' I know usin...
I suspect you have 2 versions of bash on your system, and that when you're calling bash -c '', you're invoking a different version. That or your code was altered when you created the question. As for why I think this, your code does not work on my system: $ test() { echo foo |sed -r s/.*(.)/\\1/g; } bash: syntax error...
Some bash functions run but can't be exported (no `export` failure either)
1,430,404,323,000
Why do Unix-like systems execute a new process when calling a function rather than a dynamic library? Creating a new process is costly in terms of performance when compared to calling a dynamic library.
Unix-like systems don't "call functions by executing new processes". They (now) have shared libraries like pretty much all other relatively modern operating systems. Shells on the other hand do execute other processes to do certain tasks. But not all. They have build-in functions,implemented directly in the shell (or ...
Why do Unix-like systems execute a new process when calling a new function?
1,430,404,323,000
I'm calling a function and I want to pass up to 100 paramters onto another function. I do not want to pass on the first 3 params, I start with param4 being the first param for the other program. I am currently allowing for passing on up to 19 additional with $function_under_test "$4" "$5" "$6" "$7" "$8" "$9" "${10}" ...
"${@:4}" works for me in bash. You can also assign to another array and do indexing on it: foo=("$@") second_function "${foo[@]:4}"
How can I pass on parameters 4..99 to another function
1,430,404,323,000
I have seen on many occasions a name of a function (frankly speaking I just call it function because of it typical appearance, they are though sometimes named commands or system calls but I do not know the idea behind labelling them differently), which contains a number within the brackets part of it, like in exec(1)...
exec here could be a system call or a bash built-in or something else from this . And respective man pages related to system call or bash built-in refer to the exec's man page with numbers in the brackets. So if I want to refer to manpage of bash built-in, I would say exec(1) and if I want to refer to manpage of syste...
What is the reason for having numbers within the brackets of a function ? [duplicate]
1,430,404,323,000
I made some scripts containing some functions which by design needs sudo permission. I have added those path in .bashrc for Linux and .bash_profile for MacOS so that it can be called from anywhere. But I do not want the user to type sudo each time they want to call those script functions. Is there any way I can imply...
The "$@" will expand to the list of command line arguments, individually quoted. This means that if you call your script with ./script.sh start-one it will run start-one at that point (which is your function). It also means that invoking it as ./script.sh ls it would run ls. Allowing a user to invoke the script us...
sudo without sudo, implying sudo in script
1,430,404,323,000
I've been writing a lot of one-off functions recently. On the occasions that I go "hmm, I should save this" I use type <function name> to show the code, and copy and paste it into .bashrc. Is there a faster way to do this, or some standard or command built for this purpose? FWIW, I'm just doing this on my personal com...
In Korn-like shells, including ksh, zsh, bash and yash, you can do: typeset -fp myfunc To print the definition of the myfunc function. So you can add it to the end of your ~/.bashrc with: typeset -fp myfunc >> ~/.bashrc
Correct way to take a function from the current shell and save it for future use?
1,567,691,275,000
# Print $1 $2 times function foo() { for (( i=0; i<$2; i++ )); do echo -n $1 done echo } # Print $1 $2x$3 times function bar() { for (( i=0; i<$3; i++ )); do foo $1 $2 done } bar $1 $2 $3 The ideal output of foobar.sh @ 3 3 is @@@ @@@ @@@ but the actual output seems to be just @...
Because variables are "global" in shell-scripts, unless you declare them as local. So if one function changes your variable i, the other function will see these changes and behave accordingly. So for variables used in functions --especially loop-variables like i, j, x, y-- declareing them as local is a must. See bel...
Loop function with arguments in another loop function with arguments
1,567,691,275,000
I've got the following function aliases sourced in zsh and bash consoles: compose() { docker-compose $* } run() { compose "run --rm app $*" } rails() { run "rails $*" } In bash, running rails c starts a Ruby on Rails console through docker-compose successfully. In zsh, running rails c results in a command not...
It's not zsh that's replacing dashes with underscores, but probably that docker-compose program, or another program called by it. The problem is that zsh, unlike bash, does not split unquoted variables with IFS by default. If I define docker-compose as a function that prints each of its argument surrounded by {}, this...
Why does zsh replace hyphens with underscores in these functions?
1,567,691,275,000
I use Ubuntu 16.04 with Bash and I have a file with 10 functions. Each function does essentially a different task. In the end of each function, I call it this way: x() { echo } x The calls add 10 more lines to the file, lines that I would wish to save from the file from aesthetic reasons, because I execute all fu...
If you are only concerned with the line count of your file you could do something like this: my_func () { echo "Hello, world" } && my_func
Bash: How to call all functions of a file in one single call from the command line?
1,567,691,275,000
I have the following function split in my .bash_profile file. function split { name="${$1%.*}" ext="${$1##*.}" echo filename=$name extension=$ext } Now I should expect that the command split foo.bar will give me filename=foo extension=bar But I get get -bash: ${$1%.*}: bad substitution error message. The ...
Drop the $ preceding the variable name (1) inside the parameter expansion: name="${1%.*}" ext="${1##*.}" you are already referring to the variable with the $ preceding the starting brace {, no need for another one in front of the variable name.
bash function : splitting name and extension of a file
1,567,691,275,000
I do the following to make history more sensible (i.e. seeing when a command is run can be fairly critical when troubleshooting) shopt -s histappend; # Append commands to the bash history (~/.bash_history) instead of overwriting it # https://www.digitalocean.com/community/tutorials/how-to-use-bash-history-commands...
You're almost there. You are defining a function, but using the alias keyword. Just remove the alias and you should be fine. Next, you are escaping the awk variables, but you aren't double-quoting, so the escapes are being passed to awk. This is what you're after: ho() { history "$@" | awk '{$2=$3=""; print}'; }
bash, pass an argument to the 'history' command
1,567,691,275,000
I have a loop that checks for certain criteria for whether or not to skip to the next iteration (A). I realized that if I invoke a function (skip) that calls continue, it is as if it is called in a sub-process for it does not see the loop (B). Also the proposed workaround that relies on eval-uating a string does not w...
The problem is that when your function is executed, it is no longer inside a loop. It isn't in a subshell, no, but it is also not inside any loop. As far as the function is concerned, it is a self-contained piece of code and has no knowledge of where it was called from. Then, when you run eval "$skip_str" there is no ...
continue: only meaningful in a `for', `while', or `until' loop
1,567,691,275,000
How do I pass an array to a function, especially if it is in the middle somewhere? Both "${b}" and "${b[@]}" seems to pass the first item only, so is there a way to both - call and retrieve it, correctly? #/usr/bin/env bash touch a b1 b2 b3 c f() { local a="${1}" local b="${2}" local c="${3}" ls "...
In the bash shell, like in the ksh shell whose array design bash copied, "${array[@]}" expands to all the distinct element of the array (sorted by array index), and "$array" is the same as "${array[0]}". So to pass all the elements of an array to a function, it's f "${array[@]}". Now, a function's arguments are access...
How do I pass an array as an argument?
1,567,691,275,000
I have a bash script on centos7, and I need to execute some commands as different user. But it seems sudo works as expected outside function and didn't work inside bash function. I run script as ssh [email protected] 'bash -s' < script.sh test(){ sudo -Eu root bash echo "inside $(whoami)" # other commands ...
Don't do this. Getting the two lines of output in the wrong order should have been a hint that something was wrong. When you execute your script using ssh [email protected] 'bash -s' < script.sh the following happens: The script is passed to bash -s on the shells standard input stream. The script defines the test f...
How can I change user inside function
1,567,691,275,000
I am wondering if we need to add shell title: #!/bin/bash on a script, second.sh, which only defines a function, and is called from another script, script.sh. For example, with script.sh containing #!/bin/bash source second.sh func1 "make amerika great again " echo $I_AM_SAY and second.sh containing only a functi...
No, you don’t need a shebang line: the running shell sources the script directly, it doesn’t start a new shell (which is the whole point of sourcing a script), so neither it nor the kernel need to know which shell to use to run it. If you want to prevent the second.sh script from being invoked at all, you can add a #!...
Do we need to define the shell on file that include only functions?
1,567,691,275,000
foo (){ sudo -- sh -c "cd /home/rob; echo \"$@\"" } I'm trying to make a bash function in .bashrc that will sudo, change to a particular directory and then run a Python command. For demo purposes I have changed this to echo in the above example. Even though I have quoted $@ to pass all arguments to my ech...
Add set -v to your function and you will see what is happening: $ f (){ set -v; sudo -- sh -c "cd /tmp; echo \"$@\""; } $ f 1 2 + sudo -- sh -c 'cd /tmp; echo "1' '2"' What is happening? Your use of $@ has created two strings that have been single quoted to cd /tmp; echo "1 and 2". You can use $* if you dont want ...
Passing multiple arguments to sudo within function
1,567,691,275,000
I sometimes use characters such as ! and $ in commit messages, they need to be manually escaped, but not if you use single quotes like this git commit -m 'My $message here!'. I tried to write a function to make gc and all text following as the message, but no luck in making it use single quotes. Everything I've tried,...
TL,DR: don't. What you're asking for is impossible. When you write gc My $message here, this is an instruction to expand the value of the variable message and use the expansion as part of the arguments of the function. You can do something like what you want by tricking the shell with an alias that adds a comment mark...
Run `git commit -m` with single quotes in zsh
1,567,691,275,000
What I would like to do is: f(){ ssh myserver && ls && echo 'it works!' } However, when I run this function. Only the ssh is executed.
Put the list of commands directly after ssh myserver: ssh myserver 'ls && echo it works'
I want a function to ssh into a server and then run a list of commands
1,567,691,275,000
I'm preparing for the LPIC1, exam 102. This question came my way and I absolutely blanked. I knew it when I first took the quiz, now a month and a half later it's all blurred in my head. What does function a { echo $1; } ; a a b c output? A. a B. a b c C. a b D. a a b c I've tried to reproduce this fu...
The commands should have been executed on a command line like: function a { echo $1; } ; a a b c The second semicolon separates the command list into function a { echo $1; } and a a b c The first command will create a function with the name 'a' which will echo the first positional parameter. The semicolon after ech...
Why are these particular semicolons necessary in this function definition and command-line?
1,567,691,275,000
I am using Bash 4.4.20. I typically have main function in each bashscript. If I want to source this script from another function inside another bash script, will this conflict with the main function definition in both the scripts? #A.sh main() { SomeFunction } SomeFunction(){ . B.sh } main "$@" #B.sh main(){ echo...
The other script will redefine main(), yes. Though in this particular case, I'm not sure if it matters, since the main() from script A is running when script B redefines the function. I doubt a shell would allow the redefinition to change the behavior of an already-running function. That is, given these scripts: $ ca...
Sourced Bash script, each with main function
1,567,691,275,000
I have modified a shell script i found here: https://github.com/Slympp/ConanLinuxScript But im having troubles with the function "conan_stop" The script just terminates after exec kill -SIGINT $pid The script are sending the kill command successfully but after that it just terminates with no error code or anything. A...
exec replaces the shell with the given command, like the exec() system call. When the command (the kill, here) stops, the shell no longer exists, so there's no way for the script to continue. The two exceptions are 1) when exec is given redirections, in which case it just applies them in the current shell, and 2) when...
Problem with shellscript crashing after "exec kill -SIGINT"
1,567,691,275,000
I'm working with a set of scripts with functions treated as readonly. The functions are more than just a list of commands, for example, there can be loops and change directories and even calls to other functions: func() { cd folder/ run command1 mkdir folder2/ ; cd folder2/ run command2 } For a moment...
#!/bin/bash # test.sh post() { echo "post [$BASH_COMMAND] [$?]" echo "== $RANDOM ==" } set -o functrace trap post debug func() { . check.sh tryme |& tee out.txt } func The output can be filtered by the lines marked with random. I should test this further to see how well it works with m...
Trap all commands in function
1,567,691,275,000
Suppose, for example, that fpath is set to ( $HOME/.zsh/my-functions /usr/local/share/zsh/site-functions ) ...and that both function-defining files $HOME/.zsh/my-functions/quux and /usr/local/share/zsh/site-functions/quux exist. (I'll refer to these two versions of quux as "the user's quux" and "the site's quux", res...
The easy way is to force the loading of the original function, rename it, and redefine it in your .zshrc, rather than having a function with the same name in your fpath. Note that in zsh, you don't need complex tricks involving which, eval and wondering about quoting to rename a function: simply use the functions asso...
How can a function call the function it "overrides"?
1,567,691,275,000
I'm trying to add an alias in .bashrc file as follows: ... alias cutf="_cutf" ... _cutf() { awk 'NR >= $2 && NR <= $3 { print }' < $1 } (The function's goal is to show the content of the lines whose number is between $2 and $3 for the $1 file) When I call cutf in a new bash session I get no output. Am I missing so...
$2 and $3 are in single quotes. Shell doesn't expand variables in single quotes, so they get interpreted by awk. Switch to double quotes: awk "NR >= $2 && NR <= $3 { print }" < "$1" Note that you can achieve the same with sed -n 'X,Yp' file where X and Y are the line numbers, or similarly in Perl with perl -ne 'prin...
Bash: How to create an alias in .bashrc for awk with parameters
1,567,691,275,000
For context, I'm using zsh. Every time I use locate, I want to pass the -i and -A flags. Usually, if I can get away with it, I create an alias with the same name as the existing command to do this. But according to this question, aliases can't accept arguments, so I have to use a function instead. Usually I stop there...
I am really surprised by that other post you mentioned, as it can be very misleading. Just because an alias doesn't use parameters doesn't mean that aliases cannot set parameters. Of course you can put options in an alias, but it is just restricted, meaning, the alias is replaced in one place. $ alias ls='ls -l' $ l...
How can I/Should I default flags when running a command?
1,567,691,275,000
I'm currently running a tiling window manager and I want to be able to use a custom function that is equivalent to one I had when I was using tmux that allowed me to run a command in all visible shells in the current window (E.G. ta cd to/dir) The command/function was called ta meaning "to all" I've managed to create ...
Why what you tried doesn't work Terminals are two-way communication channels between the terminal provider and the application(s) running in the terminal. The terminal device represents the side of the applications: writing to it is a request for the terminal provider to display what you wrote, and reading from it is ...
execute command on all visible shells
1,567,691,275,000
Basically something like // declare const my_func = function(param1, param2) { do_stuff(param1, param2) } // use my_func('a', 'b'); All in current interactive shell without using files
Functions are defined in the same way in an interactive bash shell as in a bash shell script. Taking your example as a starting point: my_func () { do_stuff "$1" "$2"; } You would type that on the command line. Then call that (also on the command line) with my_func 'something' 'something else' 'a third thing' Note t...
Declare and use ad-hoc function in bash in interactive shell
1,567,691,275,000
I have this script: #!/bin/bash BASE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" > /dev/null 2>&1 && pwd )" USER_DEF=$(whoami) function private { read -p "Enter private chat name: " name if [[ $name == '' ]] ; then : else if [ -d "$BASE_DIR/chats/private/$name/" ] ; then pa...
The problem is the line unset $options When $options is evaluated it contains, amongst other things, the word private so the shell undefines your function. The correct syntax is unset options
receiving error 'script.sh: line 150: private: command not found'
1,567,691,275,000
Is there a way to access docstrings in Bash? How does one include a docstring in a function's definition in Bash? More specifically how do I add and access docstrings to the following function? funky() { echo "Violent and funky!" }
If you mean "Bash's equivalent of Python's docstrings" I'm afraid I have to disappoint you that there is no such thing. However.. I must say that implementing an equivalent of the "docstrings" feature would make for a very interesting homework in order to learn Bash's programmable-completion facility along with how to...
Accessing function documentation
1,567,691,275,000
I have bash functions foo and bar in my ~/.bashrc. Function foo calls an external command ext_command that itself takes as one of its arguments another command. I want to pass bar as that command, i.e. I'd want my .bashrc to look something like this: bar() { ... } foo() { ext_command --invoke bar } However, this d...
You generally have these ways to go: Rewrite the function to command, ie. a script on its own. A common practice is to keep a ~/bin directory and include it in your $PATH. Export the function to the environment and make the other shell get it from there. See Can I "export" functions in bash? Stick to bar being a sour...
How to make my bash function known to external program
1,567,691,275,000
I have the following command to remote into a local server and tail -f the latest log file for an application that I have. The command works perfectly fine from the command line - ssh user@hostname 'tail -f $(ls -1r ~/Development/python/twitter-bot/logs/*.log | head -1)' The problem is that when I make it an alias (o...
For the alias you need some escapes alias latestbotlogs="ssh user@hostname 'tail -f \\\$\\(ls -1r \\~/Development/python/twitter-bot/logs/*.log \\| head -1\\)'" or alias latestbotlogs='ssh user@hostname '\''tail -f $(ls -1r ~/Development/python/twitter-bot/logs/*.log | head -1)'\' The second version is easier, you d...
SSH with Command Doesn't Run as an Alias
1,567,691,275,000
In this is the scenario, need to call func1 from Main_Func. How do I call it? Main_Func() { <code> } Initialize_func() { func1() { <code> } }
For func1 to be defined, you will first have to have called Initialize_func at least once. Then you may call func1 as just func1. Example: outer1 () { echo 'in outer1' inner } outer2 () { echo 'in outer2' inner () { echo 'in inner' } } # First example explained below: outer1 # Second e...
How to call sub function of a different function from current function in ksh?
1,567,691,275,000
I'm learning Bash, and I've written a basic function: wsgc () { # Wipe the global variable value for `getopts`. OPTIND=1; echo "git add -A"; while getopts m:p option; do case "${option}" in m) COMMIT_MESSAGE=$OPTARG if [ "$COMMIT_MESSAGE" ...
the if in m) isn't working, in that if I omit the argument, Bash intercedes and kicks me out of the session; You specify getopts m:p option. The : after the m means that you need an argument. If you don't provide it, it's an error. After running: wsgc -m "Yo!" -p, I get kicked out of the session. What do you mean ...
Bash: Help honing a custom function
1,567,691,275,000
function projectopen { local di_files=(*.xcworkspace */*.xcworkspace *.xcodeproj */*.xcodeproj) # open first exsit file ls -d -f -1 $di_files 2>/dev/null \ | head -1 \ | xargs open } I write a shell function to quick open xcworkspace in terminal. But when I declare di_files as a local var, then ...
In older versions of zsh you cannot initialise an array with local (or typeset/declare) like that, you need to separate it, e.g. local -a di_files # explicit array di_files=( ... ) The feature to permit declaration and array assignment together was added in v5.1. I believe the error you see is because zsh is treating...
Declare as local var will break a function and log out "1: number expected"
1,567,691,275,000
I have this function (defined inside my ~/.zshrc): function graliases { if [[ "$#*" -lt 1 ]] then echo "Usage: graliases <regex>" else echo "$*" grep -E '*"$*"*' ~/.dotfiles/zsh/aliases.zsh fi } What this function should do, is search the file ~/.dotfiles/zsh/aliases.zsh with a...
The grep pattern looks wrong. The rule of thumb of the command line is that everything inside single quotes is taken literally, whereas when not quoted or inside double quotes shell expand such string according to its rules (globing, splitting, parameter expansion etc.). In your case the command grep -E '*"$*"*' ~/.do...
$* variable of zsh function leads to unexpected results
1,567,691,275,000
I have the Linux script shown below. I can get it to return from the method decrypt nothing which I need to unzip a file. The method decrypt sends a string with the name of a zip file. Please give some advice. I mention that another methods it brings correctly the files. m_mode_verbose=1 const_1="ceva" val="valoare" ...
To answer the title of your question, shell functions usually return data by printing it to stdout. Callers capture the return value with retval="$(func "$arg1" "$arg2" "$@")" or similar. The alternative is to pass it the name of a variable to store a value in (with printf -v "$destvar"). If your script isn't workin...
Returning a variable from a function [closed]
1,567,691,275,000
I would like to have an alias for the following code:- g++ *.cc -o * `pkg-config gtkmm-3.0 --cflags --libs`; but I want that when I enter the alias it should be followed by the file name *.cc and then the name of the compiled program *. for example: gtkmm simple.cc simple should run g++ simple.cc -o simple `pkg-c...
What you need isn't an alias, but a function. Aliases do not support parameters in the way you want to. It would end just appending the files, gtkmm simple.cc simple would end like: g++ -o `pkg-config gtkmm-3.0 --cflags --libs` simple.cc simple and that's not what you try to achieve. Instead a function allows you to:...
Aliasing a command with special parameters [duplicate]
1,567,691,275,000
Namely: I want to alias tail -f to less +F but let tail with any other parameter supplied work the same way as before.
This is slightly beyond the powers of what shell aliases provide (assuming bash). You could define a function: function tail() { if [ "$1" == '-f' ]; then shift less +F "$@" else command tail "$@" fi } When you type tail, this will now refer to the function defined above, which...
Aliasing a command with parameter supplied to another command
1,567,691,275,000
How do I make the following function work correctly # Install git on demand function git() { if ! type git &> /dev/null; then sudo $APT install git; fi git $*; } by making git $* call /usr/bin/git instead of the function git()?
Like this: # Install git on demand function git() { if ! type -f git &> /dev/null; then sudo $APT install git; fi command git "$@"; } The command built-in suppresses function lookup. I've also changed your $* to "$@" because that'll properly handle arguments that aren't one word (e.g., file names with spaces)...
Install-on-Demand Wrapper Function for Executables
1,567,691,275,000
TL:DR How do I add a grep to a bash function while allowing a variable number of optional inputs? I find that in repeated grepping of large outputs, I end up clogging the terminal with data. Sometimes, I want to do a grep, and quickly go to the top of it while capturing all the data. To this end, I have become acc...
In bash and sh "$@" will expand all positional parameters so: cgrep () { clear clear grep "$@" } Note that $@ has to be double quoted to prevent word splitting, globbing, empty removal, etc from being performed on each parameter. 3.4.2 Special Parameters
Bash Function Grep Mod
1,567,691,275,000
Let's say I write a bash function like so: function.sh usage () {echo "No arguments are needed";} myfunction () { if [[ $# -qt 0 ]] ; then usage fi echo "Hello World" } Then I source function.sh. However, I have another script with usage() defined there too and I have sourced it too. I run myfunction -myWorld a...
The answer to your question, as it currently stands, is that Bash calls the last defined version of the function. Using two modified versions of your example: function1.sh usage () { echo "Usage from function1.sh - No arguments are needed"; } myfunction1 () { if [[ $# -gt 0 ]] ; then usage fi echo "Hello...
When writing a bash script, how does the script know which usage() to call?
1,567,691,275,000
I use Windows and Linux a lot, and sometimes I type cd\ from Windows muscle-memory, so I tried to alias that, alias cd\='cd /' but that doesn't work (presumably because \ is an the escape character in Linux). Is there a way, using an alias or a function that I could make typing cd\ => cd / ?
That would be hard, since the backslash is used to escape the next character, and at end of line, it starts a continuation line. So even if you could make a function called cd\, you'd need to run it as cd\\, or 'cd\'. And with aliases, escaping or quoting part of the name prevents alias expansion... Anyway, you can't ...
bash, "\" in an alias or function
1,567,691,275,000
This was my starting point: shell script - Executing user defined function in a find -exec call - Unix & Linux Stack Exchange But I need to choose between 2 different versions of the function, based on an argument passed to the containing script. I have a working version, but it has a lot of duplicate code. I'm trying...
You can export force too and move the if [[ $force == "y" ]] into the function: cmd() { if [[ $force == "y" ]] ; then git fetch; git reset --hard HEAD; git merge '@{u}:HEAD'; else git pull; fi newpkg=$(makepkg --packagelist); makepkg -Ccr; repoctl add -m $newpkg; } export -f cmd export ...
Executing user defined function in a find -exec call AND choosing version of that function based on arguments
1,567,691,275,000
I'm rocking ZSH as my main shell, but in my .zshrc, I'd like to set up a ssh command with expect so I can ssh into my dev boxes easier when I flash builds (there's literally no security needed it's all on an intranet of sorts). I can pass a password to ssh with !#/usr/bin/expect shell. Is it kosher to do this? passwor...
As already mentioned by choroba, that shebang becomes a regular commentary line. Instead having separate expect script file, you can use heredoc: function expect_ssh () { expect <<'EOF' set timeout 20 set cmd [lrange $argv 1 end] set password [lindex $argv 0] eval spawn $cmd expect "password:" send "$password\r"; in...
Change shells in a script function
1,588,657,028,000
Iam new to linux and trying to pass a variable from one function to another in a same bash script. Below is my code: #!/bin/bash -x FILES=$(mktemp) FILESIZE=$(mktemp) command_to_get_files(){ aws s3 ls "s3://path1/path2/"| awk '{print $2}' >>"$FILES" } command_to_get_filesizes(){ for file in `cat $FILES` do if ...
It depends on your use-case on how to transfer data from one function into another one. I could not reproduce your error - maybe it has something to do with aws or s3cmd. using backticks as subshell is deprecated - you should use $(). If you just want to pass data and you are not interested in storing them to your har...
Passing a variable from one function to another in bash script
1,588,657,028,000
I want to use direnv to automatically define a bash function when I switch to a particular directory. Here is the function definition. seqchart () { # Create a sequence diagram creation shorthand f=$1 target_f=${f%.*}.svg if [ -f "$f" ]; then diagrams sequence $f ${target_f} open -a fir...
From the FAQ, emphasis mine: direnv is not loading the .envrc into the current shell. It’s creating a new bash sub-process to load the stdlib, direnvrc and .envrc, and only exports the environment diff back to the original shell. This allows direnv to record the environment changes accurately and also work wit...
How to create a bash function from within a .envrc?
1,588,657,028,000
I'm trying to monitor some files with entr. My script based on their examples: do_it(){ echo Eita!; } while true; do ls folder/* more-folder/* | entr -pd do_it; done >> entr: exec do_it: No such file or directory However, this works: while true; do ls folder1/* folder2/* | entr -pd echo Eita!; done What am I doing w...
Answered by the programmers of entr (https://github.com/eradman/entr/issues/6): "A function can be exported to a subshell, but you cannot execute a function with an external program. If you want to execute shell functions, you can write a loop such as this:" do_it(){ echo 'Eita!'; } while true; do ls folder1/* fo...
Entr: trying to trigger function while monitoring file change
1,588,657,028,000
How can I "inject" a function argument to a defined variable like in this example? mood="i am $1 happy" happy () { echo "$mood" } happy "very" Current output: i am happy Desired output: i am very happy Thanks! Edit: The real world example is: I have a lot of translatable strings in another file, like so: ins...
This should work. Be very careful with eval, never use eval on user input, it will execute anything. mood='i am $1 happy' happy () { eval echo "$mood" } happy "very"
Pass function argument to defined variable
1,588,657,028,000
I executed the following code in my Bash console in an Ubuntu 16.04 environment: cat <<-'DWA' > /opt/dwa.sh DWA() { test='test' read domain find /var/www/html/ -exec cp /var/www/html/${domain} /var/www/html/${test} {} \; sed -i 's/${domain}/${test}'/g /var/www/html/test/wp-config.ph...
The last DWA is being removed because you are using this as your delimiter. The delimiters tell your shell everything between these matching strings is part of my here doc. The delimiters are not part of the doc and are therefore stripped when the here doc is read. The reason the DWA prior to that remained is becau...
cat heredocument copied everything besides function call
1,588,657,028,000
What is FreeBSD's /bin/sh equivalent to bash's: compgen -A function which lists the names of the declared functions.
FreeBSD's /bin/sh is the Almquist shell, and it has no equivalent to that because the Almquist shell does not have programmable command completion in the first place. However, if you were looking for an equivalent for typeset -F you would still be out of luck. The Almquist shell has no built-in command for listing th...
FreeBSD's sh: List functions
1,588,657,028,000
I am unable to discern why timeout in a function call will cause a loop to stop. I have a "solution", but I am really very intrigued as to how / why this is happening! It seems to be something to do with cat being the command getting timed out? TL;DR while read -r line; do ... done < file gets terminated when a time...
cat $(find . -name iamnothere.txt) | wc -l assuming that iamnothere.txt does not exist becomes cat | wc -l which consumes standard input, the same standard input that the while loop is reading the lines from. for avoids this by not using standard input like while does. This can be observed by using a bare cat for t...
timeout causes while read loop to end when `cat` is timed out
1,588,657,028,000
I am trying to execute few commands in a server by logging in using sshpass command like below. SSH_ARGS='-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -q' sshpass -p 'password' ssh ${SSH_ARGS} user@IP 'sudo sed -i "/^server 0.rhel.pool.ntp.org/ { N; s/^server 0.rhel.pool.ntp.org\n/server xxx.xx.xx.xx ib...
What you seem to be looking for is an alias: alias sp='sshpass -p "password" ssh $SSH_ARGS user@IP' You can therefore run your commands like: sp 'sudo sed -i "/^server 0.rhel.pool.ntp.org/ { N; s/^server 0.rhel.pool.ntp.org\n/server xxx.xx.xx.xx iburst\n&/ }" /etc/ntp.conf' Note that there may be ways to simplify yo...
How to use ssh in a function(bash)?
1,588,657,028,000
I wrote a bash script for listing python processes, ram usage and PID and status in human readable form with colored lines. But I have some trouble with working time of the script. Because of the repeatedly written ps commands working time is taking too much time. SCRPITS=`ps x | grep python | grep -v ".pyc" | grep -v...
I suggest you extract the info that you need from ps, nothing else, and let awk (not bash) do the rest: grepping, comparisons, formatting. Example: ps -ax --no-headers -o pid,vsz,stat,command | awk -v lim=23000 ' # let awk do the grepping /bash/ && !/awk/ { # save first 3 fields pid=$1 vsz=$2 stat=$3 # rest ...
How to split Bash array into arguments
1,588,657,028,000
Overview: I save my variable in a config file and call them later. Each entry with the name FailOverVM has a number beside it like FailOverVM1 and I want to check to see if it has data and generate a function named FailOverVM1() that later in the script starts $FailOverVM1Name, which happens to be 'Plex Server' I can...
Asides: you can eliminate the wc -l by using grep -c FailoverVM.Name configfile. But if you want to use numbers over 9 decimal (not e.g. 123456789abcdef) your pattern needs to be FailoverVM[0-9][0-9]?Name or FailoverVM[0-9]{1,2}Name in -E extended mode. Also for i $VMCount is a syntax error; I assume you mean for i in...
Func name as variable in loop
1,588,657,028,000
FuzzyTime() { local tmp=$( date +%H ) case $((10#$tmp)) in [00-05] ) wtstr="why don't you go to bed" ;; [06-09] ) wtstr="I see your very eager to start the day" ;; [10-12] ) wtstr="and a very good day too you" ;; [13-18] ) wtstr="Good Afternoon" ...
[] denotes character ranges: [10-12] means digits 1 2 and the range between digits 0-1 -- this will match a single digit in range 0-2. Use simple comparisons with if-elif-else-fi: if [ "$tmp" -ge 0 ] && [ "$tmp" -le 5 ]; then echo "<0,5>" elif [ "$tmp" -ge 6 ] && [ "$tmp" -le 9 ]; then echo "<6,9>" #... else #...
case statement not behaving as expected (fuzzytime() function)
1,588,657,028,000
I want to use an argument in the function I created in my .profile file. I want to ask for input if no argument is given, otherwise set a variable to $1. When I check $1 to see if it is empty, I get the following error: sh[7]: 1: Parameter not set. From the following line: if [ ! -n "$1" ]; then I'm using sh not ba...
I think there's more to this: Either that's not the command you're using - or else somewhere else in the function you're doing it differently. That error comes from ${1?}. Or it comes from your test, but only if you first do set -u. To fix that, stop doing that. Do set +u; fn_name, and see what happens. And if you hav...
sh - Using Arguments in .profile functions
1,588,657,028,000
In bash I can do: foo() { echo bar; } export -f foo perl -e 'system "bash -c foo"' I can also access the function definition: perl -e 'print "foo".$ENV{"BASH_FUNC_foo%%"}' How do I do the same in fish? Edit: With this I can get the function definition: functions -n | perl -pe 's/,/\n/g' | while read d; functions $d;...
Ugly as hell, but works: function foo echo bar; end setenv funcdefs (functions -n | perl -pe 's/,/\n/g' | while read d; functions $d; end|perl -pe 's/\n/\001/') perl -e '$ENV{"funcdefs"}=~s/\001/\n/g;system ("fish", "-c", $ENV{funcdefs}."foo")'
Accessing fish functions from perl
1,588,657,028,000
I'm writing a function, adding it to ~/.zshrc on my Mac. It's in order to more quickly handle commands to youtube-dl. I have this: function dlv() { cd /Users/admin/Downloads youtube-dl -f 'best' "$1" } But when I make a request I have to input the youtube link with quote marks. dlv "https://www.youtu...
Well, zsh could quote the URLs for you via functions and zle - the line editor: autoload -Uz url-quote-magic zle -N self-insert url-quote-magic autoload -Uz bracketed-paste-magic zle -N bracketed-paste bracketed-paste-magic and then when you type or paste a URL in your terminal it'll be automatically quoted. Another...
How to write a function that takes an argument string that does not need to be quoted?
1,588,657,028,000
I have a zsh alias: gitbs() { git branch | grep -- $1 } And I would like to pass the result into git checkout, for example: git checkout | gitbs state How can I make this work?
A shell pipe passes the output of a command to the input of another command. This won't help you here: you want to pass the output of a command as a command line argument of another command. The tool for that is command substitution. So the basic idea is git checkout "$(gitbs state)" (It's still a pipe under the hood...
How to pass zsh alias function to pipe
1,588,657,028,000
I have a somewhat difficult time figuring out how - if possible - to return from a higher function, let me show you a POSIX code tidbit: sudoedit_err () { printf >&2 'Error in sudoedit_run():\n' printf >&2 '%b\n' "$@" } sudoedit_run () { # `sudoedit` is part of `sudo`'s edit feature if ! command -v su...
A couple of people have suggested a subshell, which I think is a good idea. Using that, you can introduce a wrapper function that invokes a second function in a subshell. With that, any function that that second function calls can invoke exit to terminate the subshell. Here's an example based on your original post: ...
Return from higher function, how - if possible?
1,588,657,028,000
I'm quite new on the shell scripting front and was wondering whether it is is possible to call a function which itself than calls another function with none, one or multiple arguments. The first argument would be the name of the function to call, every other argument is an argument for the function to call. As a backg...
In Bourne-like shells "$@" (note that the quotes are important!) expands to all the arguments of the script, or function if expanded inside a function, so here: runSerialOrParallel() { if [ "$n_core" -eq 1 ]; then runSerial "$@" else runParallel "$@" fi } Would make runSerialOrParallel inv...
call function by name with arguments
1,588,657,028,000
I am trying to create output from my Bash script which includes hostname, SSH protocol, and root login information. I would like to do it using Bash functions. I have a .sh file but it does not work. Where is the problem in this code? Server Version: Red Hat 7 The expected output would be: xyz|hostname|Protocol X|Roo...
The poor indentation and layout of your script muddles the question, but the basic answer is printf '%s|%s|%s|%s\n' "$(field1)" "$(field2)" "$(field3") "$(field4)" Refactored into this, and with indentation etc cleaned up, your script becomes #!/bin/bash host(){ hostname } protocol(){ # avoid useless use of...
Using Multiple Function to get an output in a single Line
1,588,657,028,000
unalias removes / disables an alias for the current session, that is, an alias is temporally disabled. If an alias is wrong, undesired or no more useful, I simply delete it from .bashrc or .bash_alias and source ~/.bashrc or close and reopen my terminal. A usage I have found for unalias was when, after creating an ali...
If an alias is wrong, undesired or no more useful, I simply delete it from .bashrc or .bash_alias and source ~/.bashrc or close and reopen my terminal. "Why would I want to wash my hands if I can just take a shower"? Oftentimes that is an impossible or an undesirable action. For instance, suppose you had a bunch of ...
When and why unalias?
1,588,657,028,000
I'm sure this is fairly elementary, but I can't figure it out. My script: #!/bin/bash sez () { echo $1 spd-say "$1" } sez "does this work" sez "this does work" What I'm trying to make happen is use spd-say in a function to make the computer talk to me. The echo portion of my function works. It outputs both lines...
I had a similar problem and I found a workaround. Instead of using spd-say I used espeak directly.
Using spd-say in a bash script function
1,588,657,028,000
I'm no so advanced in bash so can not make my function work properly. Here is the code: archive() { for f in $PWD do for ((i=1; i++;)) do 7za a "$1".7z $f -pSECRET -mhe done done } In order this function should take arbitrary amount of parameters like archive foo file1.txt file2.jpg file3.asc ....
Why are you iterating over $PWD? that is not a list. To iterate over all arguments to a script or function, use for ARG in "$@"; do or the short form for ARG; You can use "shift" to save the first parameter to a variable, then use the loop as above to iterate over the rest of the parameters. For the GPG part, you j...
Function for archiving arbitrary files with encryption
1,588,657,028,000
I have had this function I use it very often and it works fine. Here it is: cdx () { cd `dirname $1` ; } However, this does not work with spaces. When I use it like this for example cdx ~/desktop/folder/file\ file It returns usage: dirname path But what I am passing is, essentially dirname path. So what am I suppo...
If you simply write $i, spaces will turn your variable content in multiple arguments. If you want to preserve spaces you have to quote things. For your example you probably want: cdx () { cd -- "$(dirname -- "$1")" ; } And remember always quote your variables.
Why doesn't my function work with spaces? (cd, dirname) [duplicate]
1,588,657,028,000
I am writing a bash function that takes a number of strings, with each string to be printed it a separate line. But have to compose the frmt variable to printf appropriately depending on the number of strings being passed to the function. print () { case $1 in h|-h|-\?|--help) printf "Prints a text string....
No need to build a format string according to number of arguments. To quote the link by Mr. Thompson: The format argument is reused as necessary to convert all the given arguments. For example, the command ‘printf %s a b’ outputs ‘ab’. Write test code. When working with things like this, break it down as much you ...
printf format depending on number of parameters
1,588,657,028,000
So for example adding an ending to the command would display the ending: function work* () { echo "$1"; } export -f work* $ working ing
Perhaps something like the following would do it for you: function work() { echo "${1#work}" } function err_work() { [ "${1#work}" != "$1" ] && work $* } trap "err_work \$BASH_COMMAND" ERR The err_work function is then invoked on all command errors, to discover that the failing command starts with "work", and...
Is there a way to use a function with an ending?
1,478,106,400,000
I've got the following situation: I'm writing a script that will read its parameters either from a config file (if exists and parameter present) or asks the user to input said parameter if it's not present. Since I'm doing this for a handful of parameters I thought writing a function would be the way to go. However, a...
Alright, looks like I solved my own problem: function getParameter { if [ -z "$3" ]; then # User read -p to show a prompt rather than using echo for this read -p "$2`echo $'\n> '`" parameter # Print to sdterr and return 1 to indicate failure if [ -z "$parameter" ]; then ...
Bash function assign value to passed parameter
1,478,106,400,000
Using a vim function, I would like to check if a program is running using pgrep, and if it is not running then do something. In particular, I want to achieve something like this: function! checkifrunning(mystring) if 'pgrep "mystring"' shows that something is NOT running --do something-- endif endfunct...
function! checkifrunning(mystring) if !system('pgrep "' . a:mystring . '"') " --do something-- endif endfunction Technically ! operates on Numbers, and converts a String to a Number first if given a String. However, if there's no process running, the output of pgrep will be empty, which when converted...
VIM: function that checks if external program is running
1,478,106,400,000
I am trying to write a bash script with a function which you use to send an email from the command line to an address and include a Cc address, a subject line, and an input file. For example, if the function is called "m," the typed command would look like: m [email protected] [email protected] SubjectLine TextFile.tx...
#!/bin/bash m() { to_addr="$1" cc_addr="$2" subject="$3" body="$4" cat "$body" | mail -s "$subject" -c "$cc_addr" "$to_addr" } if [[ "$#" -eq 4 ]]; then m "$1" "$2" "$3" "$4" else echo "Incorrect number of paramaters. Aborting." echo "Example syntax: $0 [email protected] [email prote...
Script to send mail using function
1,478,106,400,000
I've tried several modifications to see why it's not working, but I can't find the answer. Here is my code, this is in french but this is just a normal fonction that ask to the user if he's ready to start. #!/bin/ksh function start { echo "Vous etes sur le point de lancer la generation, etes-vous pret(e)? [OUI/N...
My file was saved in DOS Format, I used dos2unix start.sh to convert it.
A basic function that doesn't work [duplicate]
1,478,106,400,000
I'm making a .bashrc function to get me around the system faster. I used a case statement to state where I want to go. function da() { case "$1" in home) cd ~ ;; eolas) cd /home/eolas/ ;; esac } I want to import the cases from a JSON file, example: { "cases": { "home": "~", ...
Not exactly elegant, but seems to work: in=' { "cases": { "home": "~", "eolas": "/home/eolas/", "jdan": "/home/jdan/", "kl": "/.kl/" } } ' case="$(echo "$in" | perl -pe 's/"cases". \{/case "\$1" in/; s/: /) eval cd /; s/,/;;/; s...
Bashrc function case statement to import cases from JSON
1,478,106,400,000
I want to detect online network/shell services in my Solaris. I write following script for this purpose: compare_ser() { if [ "$1" != "" ]; then echo "True" >> Solaris.txt fi } export -f compare_ser svcs network/shell | cut -d ' ' -f1 | grep "online" | xargs -n1 bash -c 'compare_ser $@' when i run svcs network/shell ...
Use this: svcs network/shell | cut -d' ' -f1 | grep "online" | xargs -n1 -I{} bash -c 'compare_ser {}' The {} interpolates each value generated through xargs. Your $@ attempts to interpolate command line arguments - of which there are none.
Problem with entire function in a script
1,478,106,400,000
I currently have two bash functions, one which uploads, and another that downloads a file. I would like to create a bash script that allows users to specify which of the two they would like to do. The issue I am having is the upload and download function run no matter what. For example: function upload() { var=$1 ...
You need to call the main function too, and pass the script's command line arguments to it: #!/bin/sh upload() { echo "upload called with arg $1" } download() { echo "download called with arg $1" } main() { case "$1" in -d) download "$2";; -u) upload "$2";; *) echo "Either -d or -...
How to create a main bash script that allows users to input which of 2 functions they want to run?
1,478,106,400,000
Can somebody explain me, why the return value of a bash function is always echoed in the function and then consumed by my_var=$(my_func arg1 arg2 ..), when i look through code examples. my_func () { echo "$1 , $2, $3" } my_var=$(my_func .. .. ..); instead of using this, which would not open a subshell decla...
Standard tools and utilities return information via stdout, qualifying the result with the exit status (0=ok, otherwise error). Your functions should do the same so that they can be used in the same consistent manner. Your example shows a single global variable for all function returns. As soon as you take this approa...
return value of a function
1,478,106,400,000
I find this function online. It's does creating a directory and changing to directory. But I want to know every part of it. function mkdircd () { mkdir -p "$@" && eval cd "\"\$$#\""; }
You can pass in a list of names. It will create directories for each of them, then cd into the last one. This does not need eval. I would write it like this: mkdircd () { mkdir -p "$@" && cd "${!#}"; } ${!#} uses indirect expansion: $# is the number of parameters, so ${!#} is the value of the last parameter
Please explain below bash function
1,478,106,400,000
As https://stackoverflow.com/a/13864829/ said, $ if [ -z ${aaa+x} ]; then echo "aaa is unset"; else echo "aaa is set"; fi aaa is unset can test if a variable aaa is set or unset. How can I wrap the checking into a function? In bash, the following nested parameter expansion doesn't work: $ function f() { if [ -z ${$...
The -v test in bash will be true if the named variable has been set. if [ -v aaa ]; then echo 'The variable aaa has been set' fi From help test in bash: -v VAR True if the shell variable VAR is set. As a function: testset () { if [ -v "$1" ]; then printf '%s is set\n' "$1" else p...
How can I wrap this checking of variable set/unset into a function?