date
int64
1,220B
1,719B
question_description
stringlengths
28
29.9k
accepted_answer
stringlengths
12
26.4k
question_title
stringlengths
14
159
1,328,908,576,000
This site says, "Shell functions are faster [than aliases]. Aliases are looked up after functions and thus resolving is slower. While aliases are easier to understand, shell functions are preferred over aliases for almost every purpose." Given that (true or not), how do shell functions compare to standalone shell scr...
The main difference between aliases and functions is that aliases don't take arguments¹, but functions do. When you write something like alias l='ls --color', l foo is expanded to ls --color foo; you can't grab foo into the alias expansion and do something different with it the way you can do with a function. See also...
Aliases vs functions vs scripts [duplicate]
1,328,908,576,000
I have command foo, how can I know if it's binary, a function or alias?
If you're on Bash (or another Bourne-like shell), you can use type. type command will tell you whether command is a shell built-in, alias (and if so, aliased to what), function (and if so it will list the function body) or stored in a file (and if so, the path to the file). Note that you can have nested cases, such a...
How to test if command is alias, function or binary?
1,328,908,576,000
In Advanced Bash-Scripting Guide, in example 27-4, 7-th line from the bottom, I've read this: A function runs as a sub-process. I did a test in Bash, and it seems that the above statement is wrong. Searches on this site, Bash Man, and my search engine don't bring any light. Do you have the answer and would like to e...
The Advanced Bash-Scripting Guide is not always reliable and its example scripts contain out-dated practices such as using the effectively deprecated backticks for command substitution, i.e., `command` rather than $(command). In this particular case, it’s blatantly incorrect. The section on Shell Functions in the (can...
Do functions run as subprocesses in Bash?
1,328,908,576,000
Is it possible to call a function which is declared below in bash? Example if [ "$input" = "yes" ]; then YES_FUNCTION elif [ "$input" = "no" ]; then NO_FUNCTION else exit 0; fi YES_FUNCTION() { ..... ..... } NO_FUNCTION() { ..... ..... }
Like others have said, you can't do that. But if you want to arrange the code into one file so that the main program is at the top of the file, and other functions are defined below, you can do it by having a separate main function. E.g. #!/bin/sh main() { if [ "$1" = yes ]; then do_task_this else ...
call function declared below
1,328,908,576,000
I have a function which converts epoch time to date. Here is the definition date1(){ date -d @$1 } I'd like to be able to write: $ date1 xxxyyy Where xxxyyy is the parameter I pass into my function so I can get the corresponding date. I understand I have to add it in either .bash_profile, .profile, or .bashrc and ...
From man bash: When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and r...
How to add a function to .bash_profile/.profile/bashrc in shell?
1,328,908,576,000
Sometimes I need to divide one number by another. It would be great if I could just define a bash function for this. So far, I am forced to use expressions like echo 'scale=25;65320/670' | bc but it would be great if I could define a .bashrc function that looked like divide () { bc -d $1 / $2 }
I have a handy bash function called calc: calc () { bc -l <<< "$@" } Example usage: $ calc 65320/670 97.49253731343283582089 $ calc 65320*670 43764400 You can change this to suit yourself. For example: divide() { bc -l <<< "$1/$2" } Note: <<< is a here string which is fed into the stdin of bc. You don't ne...
Doing simple math on the command line using bash functions: $1 divided by $2 (using bc perhaps)
1,328,908,576,000
I want to write the following bash function in a way that it can accept its input from either an argument or a pipe: b64decode() { echo "$1" | base64 --decode; echo } Desired usage: $ b64decode "QWxhZGRpbjpvcGVuIHNlc2FtZQo=" $ b64decode < file.txt $ b64decode <<< "QWxhZGRpbjpvcGVuIHNlc2FtZQo=" $ echo "QWxhZGRpbjp...
See Stéphane Chazelas's answer for a better solution. You can use /dev/stdin to read from standard input b64decode() { if (( $# == 0 )) ; then base64 --decode < /dev/stdin echo else base64 --decode <<< "$1" echo fi } $# == 0 checks if number of command line arguments is z...
Bash function that accepts input from parameter or pipe
1,328,908,576,000
Suppose you have an alias go, but want it to do different things in different directories? In one directory it should run cmd1, but in another directory it should run cmd2 By the way, I have an aliases for switching to the above directories already, so is it possible to append the go alias assignment to the foo alias?...
It is not completely sure what you are asking, but an alias just expands to what is in the alias. If you have two aliases, you can append the different commands, even aliases. alias "foo=cd /path/to/foo; go" alias "foo2=cd /path/to/foo2; go" In any other situation, you could specify a function in your .bashrc functio...
How to set an alias on a per-directory basis?
1,328,908,576,000
I use Ubuntu 16.04 with the native Bash on it. I'm not sure if executing #!/bin/bash myFunc() { export myVar="myVal" } myFunc equals in any sense, to just executing export myVar="myVal". Of course, a global variable should usually be declared outside of a function (a matter of convention I assume, even if techni...
Your script creates an environment variable, myVar, in the environment of the script. The script, as it is currently presented, is functionally exactly equivalent to #!/bin/bash export myVar="myVal" The fact that the export happens in the function body is not relevant to the scope of the environment variable (in th...
Exporting a variable from inside a function equals to global export of that variable?
1,328,908,576,000
When I use df or mount, I'm most of all interested in physical disk partitions. Nowadays the output of those commands is overwhelmed by temporary and virtual filesystems, cgroups and other things I am not interested in on a regular basis. My physical partitions in the output always start with '/', so I tried making al...
You can solve the df1 argument issue by using the following alias: alias df1='df --type btrfs --type ext4 --type ext3 --type ext2 --type vfat --type iso9660' make sure to add any other type (xfs, fuseblk (for modern NTFS support, as @Pandya pointed out), etc) you're interested in. With that you can do df1 -h and get ...
show only physical disks when using df and mount
1,328,908,576,000
A few times when I read about programming I came across the "callback" concept. Funnily, I never found an explanation I can call "didactic" or "clear" for this term "callback function" (almost any explanation I read seemed to me enough different from another and I felt confused). Is the "callback" concept of programmi...
In typical imperative programming, you write sequences of instructions and they are executed one after the other, with explicit control flow. For example: if [ -f file1 ]; then # If file1 exists ... cp file1 file2 # ... create file2 as a copy of a file1 fi etc. As can be seen from the example, in imperativ...
Is the "callback" concept of programming existent in Bash?
1,328,908,576,000
I have setup several functions in my .bashrc file. I would like to just display the actual code of the function and not execute it, to quickly refer to something. Is there any way, we could see the function definition?
The declare builtin's -f option does that: bash-4.2$ declare -f apropos1 apropos1 () { apropos "$@" | grep ' (1.*) ' } I use type for that purpose, it is shorter to type ;) bash-4.2$ type apropos1 apropos1 is a function apropos1 () { apropos "$@" | grep ' (1.*) ' }
Display the function body in Bash
1,328,908,576,000
Elsewhere I have seen a cd function as below: cd() { builtin cd "$@" } why is it recommended to use $@ instead of $1? I created a test directory "r st" and called the script containing this function and it worked either way $ . cdtest.sh "r st" but $ . cdtest.sh r st failed whether I used "$@" or "$1"
Because, according to bash(1), cd takes arguments cd [-L|[-P [-e]] [-@]] [dir] Change the current directory to dir. if dir is not supplied, ... so therefore the directory actually may not be in $1 as that could instead be an option such as -L or another flag. How bad is this? $ cd -L /var/t...
Why do I need to use cd "$@" instead of cd "$1" when writing a wrapper for cd?
1,328,908,576,000
Suppose I have in main.sh: $NAME="a string" if [ -f $HOME/install.sh ] . $HOME/install.sh $NAME fi and in install.sh: echo $1 This is supposed to echo "a string", but it echoes nothing. Why?
Michael Mrozek covers most of the issues and his fixes will work since you are using Bash. You may be interested in the fact that the ability to source a script with arguments is a bashism. In sh or dash your main.sh will not echo anything because the arguments to the sourced script are ignored and $1 will refer to...
Passing variables to a bash script when sourcing it
1,328,908,576,000
From the bash manual The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at least one complete line of input before executing any of the commands on that line. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appe...
Aliases are expanded when a function definition is read, not when the function is executed … $ echo "The quick brown fox jumps over the lazy dog." > myfile   $ alias myalias=cat   $ myfunc() { > myalias myfile > }   $ myfunc The quick brown fox jumps over the lazy dog.   $ alias myalias="ls -l"   $ myalias myfile...
Alias and functions
1,328,908,576,000
I want to make an alias for a multiline ​command to call it faster then copying-pasting-executing it from a text file each time. An example for such command is this execute-a-remote-updater command: ( cd "${program_to_update_dir}" wget https://raw.githubusercontent.com/USER/PROJECT/BRANCH/update.sh source update.sh rm...
It's not impossible at all. alias thing='( cd "${program_to_update_dir}" wget "https://raw.githubusercontent.com/USER/PROJECT/BRANCH/update.sh" source update.sh rm update.sh )' or, alias thing='( cd "${program_to_update_dir}"; wget "https://raw.githubusercontent.com/USER/PROJECT/BRANCH/update.sh"; source update.sh; r...
How to make a multiline alias in Bash?
1,328,908,576,000
In bash scripts I try to keep my variables local to functions wherever I can and then pass what I need out of functions like bellow #!/bin/bash function FUNCTION() { local LOCAL="value" echo "$LOCAL" # return this variable } GLOBAL=$(FUNCTION) echo "$GLOBAL" But is it possible to do this while including ...
Anything that's printed by the function can be captured if you capture the right output stream. So the easiest way to print something and save some other output is to redirect the superfluous output to standard error: function FUNCTION() { local LOCAL="value" echo "$LOCAL" echo "This function is done now" ...
Bash Scripting echo locally in a function
1,328,908,576,000
I'm trying to create a function method in a bash script that executes a command which is supplied to the method by the paramters. Meaning somethings like this: special_execute() { # Some code # Here's the point where the command gets executed $@ # More code } special_execute echo "abc" I already tr...
I think it's just a quoting issue when you're passing the arguments into the function. Try calling it like so: $ special_execute "echo 'abc'" 'abc' If you don't want the single quotes around abc then change the quoting like this: $ special_execute "echo abc" abc Debugging You can wrap the internals of the function s...
Execute command supplied by function parameters
1,328,908,576,000
I have a function for quickly making a new SVN branch which looks like so function svcp() { svn copy "repoaddress/branch/$1.0.x" "repoaddress/branch/dev/$2" -m "dev branch for $2"; } Which I use to quickly make a new branch without having to look up and copy paste the addresses and some other stuff. However for the m...
function svcp() { msg=${3:-dev branch for $2} svn copy "repoaddress/branch/$1.0.x" "repoaddress/branch/dev/$2" -m "$msg"; } the variable msg is set to $3 if $3 is non-empty, otherwise it is set to the default value of dev branch for $2. $msg is then used as the argument for -m.
Optional parameters in bash function
1,328,908,576,000
I have a bash script as below which installs zookeeper but only if not installed already. ##zookeper installZook(){ ZOOK_VERSION="3.4.5" ZOOK_TOOL="zookeeper-${ZOOK_VERSION}" ZOOK_DOWNLOAD_URL="http://www.us.apache.org/dist/zookeeper/${ZOOK_TOOL}/${ZOOK_TOOL}.tar.gz" if [ -e $DEFAULT_...
TL;DR Use return instead of exit AND run your script with source your-script.sh aka. . your-script.sh Full details If launching a script with an exit statement in it, you have to launch it as a child of you current child. If you launch it inside the current shell of started with your terminal session (using . ./<scri...
Exit the bash function, not the terminal
1,328,908,576,000
I'd like to write a function that I can call from a script with many different variables. For some reasons I'm having a lot of trouble doing this. Examples I've read always just use a global variable but that wouldn't make my code much more readable as far as I can see. Intended usage example: #!/bin/bash #myscript.sh...
To call a function with arguments: function_name "$arg1" "$arg2" The function refers to passed arguments by their position (not by name), that is $1, $2, and so forth. $0 is the name of the script itself. Example: #!/bin/bash add() { result=$(($1 + $2)) echo "Result is: $result" } add 1 2 Output ./script.s...
How to pass parameters to function in a bash script?
1,328,908,576,000
The problem is that when watch is executed it runs sh and I get this error: sh: 1: func1: not found here is the code: #!/bin/bash func1(){ echo $1 } export -f func1 watch func1
The default shell for watch is /bin/sh. Shells will not inherit exported variables or functions from other types of shell. If your system does not symlink /bin/sh to /bin/bash (or your current shell) then you can instruct watch to exec your shell by using -x or --exec: watch -x bash -c "my_func" or watch --exec bash ...
How to force watch to run under bash
1,328,908,576,000
Using extended Unicode characters is (no-doubt) useful for many users. Simpler shells (ash (busybox), dash) and ksh do fail with: tést() { echo 34; } tést But bash, mksh, lksh, and zsh seem to allow it. I am aware that POSIX valid function names use this definition of Names. That means this regex: [a-zA-Z_][a-zA-Z0-...
Since POSIX documentation allow it as an extension, there's nothing prevent implementation from that behavior. A simple check (ran in zsh): $ for shell in /bin/*sh 'busybox sh'; do printf '[%s]\n' $shell $=shell -c 'á() { :; }' done [/bin/ash] /bin/ash: 1: Syntax error: Bad function name [/bin/bash] [/bin/da...
Shell valid function name characters
1,328,908,576,000
Sometimes I define a function that shadows an executable and tweaks its arguments or output. So the function has the same name as the executable, and I need a way how to run the executable from the function without calling the function recursively. For example, to automatically run the output of fossil diff through co...
Use the command shell builtin: bash-4.2$ function date() { echo 'at the end of days...'; } bash-4.2$ date at the end of days... bash-4.2$ command date Mon Jan 21 16:24:33 EET 2013 bash-4.2$ help command command: command [-pVv] command [arg ...] Execute a simple command or display information about commands. ...
Running an executable in PATH with the same name as an existing function
1,328,908,576,000
Is there a way to test whether a shell function exists that will work both for bash and zsh?
If you want to check that there's a currently defined (or at least potentially marked for autoloading) function by the name foo regardless of whether a builtin/executable/keyword/alias may also be available by that name, you could do: if typeset -f foo > /dev/null; then echo there is a foo function fi Though note t...
Test for function's existence that can work on both bash and zsh?
1,328,908,576,000
I have defined a bash function in my ~/.bashrc file. This allows me to use it in shell terminals. However, it does not seem to exist when I call it from within a script. How can I define a bash function to be used by scripts as well?
~/.bash_profile and ~/.bashrc are not read by scripts, and functions are not exported by default. To do so, you can use export -f like so: $ cat > script << 'EOF' #!/bin/bash foo EOF $ chmod a+x script $ ./script ./script: line 2: foo: command not found $ foo() { echo "works" ; } $ export -f foo $ ./script works exp...
How to define a Bash function that can be used by different scripts
1,328,908,576,000
I’d like to implement a function in Bash which increases (and returns) a count with every call. Unfortunately this seems non-trivial since I’m invoking the function inside a subshell and it consequently cannot modify its parent shell’s variables. Here’s my attempt: PS_COUNT=0 ps_count_inc() { let PS_COUNT=PS_COUN...
To get the same output you note in your question, all that is needed is this: PS1='${PS2c##*[$((PS2c=0))-9]}- > ' PS2='$((PS2c=PS2c+1)) > ' You need not contort. Those two lines will do it all in any shell that pretends to anything close to POSIX compatibility. - > cat <<HD 1 > line 1 2 > line $((PS2c-1)) 3 ...
Stateful bash function
1,328,908,576,000
Data 1 \begin{document} 3 Code #!/bin/bash function getStart { local START="$(awk '/begin\{document\}/{ print NR; exit }' data.tex)" echo $START } START2=$(getStart) echo $START2 which returns 2 but I want 3. I change unsuccessfully the end by this answer about How can I add numbers in a bash scr...
I'm getting 2 from your code. Nevertheless, you can use the same technique for any variable or number: local start=1 (( start++ )) or (( ++start )) or (( start += 1 )) or (( start = start + 1 )) or just local start=1 echo $(( start + 1 )) etc.
How to increment local variable in Bash?
1,328,908,576,000
So I am editing bashrc constantly, and I have a terminal open with a working function definition, although bashrc has been updated with a wrong function definition. (Because the definition do not change until I source the updated bashrc) How can I look up the working function definition in this case? For example, if I...
typeset -f function displays the indicated function's current definition. It works in ksh (where it originated), bash and zsh. (n.b. in zsh, type -f, which, functions and whence -f also show the function definition.)
View shell function's current definition
1,328,908,576,000
I encountered this error when updating bash for the CVE-2014-6271 security issue: # yum update bash Running transaction (shutdown inhibited) Updating : bash-4.2.47-4.fc20.x86_64 /bin/sh: error importing function definition for `some-function'
[edited after 1st comment from: @chepner - thanks!] /bin/bash allows hyphens in function names, /bin/sh (Bourne shell) does not. Here, the offending "some-function" had been exported by bash, and bash called yum which called /bin/sh which reported the error above. fix: rename shell functions to not have hyphens man ...
/bin/sh: error importing function definition for `some-function'
1,328,908,576,000
Is there any way I can redefine a bash function in terms of its old definition? For example I would like to add the following block of code to the preamble of the function command_not_found_handle (), # Check if $1 is instead a bash variable and print value if it is local VAL=$(eval echo \"\$$1\") if [ -n "$VAL" ] && ...
You can print out the current definition of the function, and then include it in a function definition inside an eval clause. current_definition=$(declare -f command_not_found_handle) current_definition=${current_definition#*\{} current_definition=${current_definition%\}} prefix_to_add=$(cat <<'EOF' # insert code he...
How do I redefine a bash function in terms of old definition?
1,328,908,576,000
Here is my code: function update_profile { echo "1. Update Name" echo "2. Update Age" echo "3. Update Gender" echo "Enter option: " read option case $option in 1) update_name ;; 2) update_age ;; 3) update_gender ;; esac function update_name { ech...
Yes, it's possible. It is even possible to nest a function within another function, although this is not very useful. f1 () { f2 () # nested { echo "Function \"f2\", inside \"f1\"." } } f2 # Gives an error message. # Even a preceding "declare -f f2" wouldn't help. echo f1 # Does nothing...
Is it possible to add a function within a function?
1,328,908,576,000
I have a Bash script that's getting quite long. It would be nice if I could list all the functions in it. Even better would be listing the name of the function and any documentation about its usage, eg parameters.
In general, it's impossible to list all functions without executing the script, because a function could be declared by something like eval $(/some/program). But if the functions are declared “normally”, you can search for things that look like function definitions. grep -E '^[[:space:]]*([[:alnum:]_]+[[:space:]]*\(\)...
How do you list all functions and aliases in a specific script?
1,328,908,576,000
I'm trying to create a bash alias, where the alias itself has a space in it. The idea is that the alias (i.e. con) stands for sudo openvpn --config /path/to/my/openvpn/configs/. Which results in a readable command, when the con alias is used. i.e: `con uk.conf` == `sudo openvpn --config /path/to/my/openvpn/configs/uk....
Yes, you will need to use a function. An alias would work if you wanted to add a parameter, any arguments given to aliases are passed as arguments to the aliased program but as separate parameters, not simply appended to what is there. To illustrate: $ alias foo='echo bar' $ foo bar $ foo baz bar baz As you can see, ...
Bash alias with a space as a part of the command
1,512,259,936,000
I defined the function f in Bash based on the example here (under "An option with an argument"): f () { while getopts ":a:" opt; do case $opt in a) echo "-a was triggered, Parameter: $OPTARG" >&2 ;; \?) echo "Invalid option: -$OPTARG" >&2 return 1 ;; :) ...
bash getopts use an environment variable OPTIND to keep track the last option argument processed. The fact that OPTIND was not automatically reset each time you called getopts in the same shell session, only when the shell was invoked. So from second time you called getopts with the same arguments in the same session,...
Bash function with `getopts` only works the first time it's run
1,512,259,936,000
In bash, I can write: caller 0 and receive the caller context's: Line number Function Script name This is extremely useful for debugging. Given: yelp () { caller 0; } I can then write yelp to see what code lines are being reached. I can implement caller 0 in bash as: echo "${BASH_LINENO[0]} ${FUNCNAME[1]} ${BASH_S...
I don't think there's a builtin command equivalent, but some combination of these four variables from the zsh/Parameter module can be used: funcfiletrace This array contains the absolute line numbers and corresponding file names for the point where the current function, sourced file, or (if EVAL_LINENO is set) e...
function's calling context in zsh: equivalent of bash `caller`
1,512,259,936,000
I must be missing something incredibly simple about how to do this, but I have a simple script: extract () { if [ -f $1 ] ; then case $1 in *.tar.bz2) tar xvjf $1 ;; *.tar.gz) tar xvzf $1 ;; *.tar.xz) tar xvJf $1 ;; *.bz2) bunzip2 $1 ;; *.rar) unrar ...
You're mixing up scripts and functions. Making a script A script is a standalone program. It may happen to be written in zsh, but you can invoke it from anywhere, not just from a zsh command line. If you happen to run a script written in zsh from a zsh command line or another zsh script, that's a coincidence that does...
How to make custom zsh script executable automatically?
1,512,259,936,000
Hello I have this in my ~/.bash_profile export GOPATH="$HOME/go_projects" export GOBIN="$GOPATH/bin" program(){ $GOBIN/program $1 } so I'm able to do program "-p hello_world -tSu". Is there any way to run the program and custom flags without using the quotation marks? if I do just program -p hello_world -tSu...
Within your program shell function, use "$@" to refer to the list of all command line arguments given to the function. With the quotes, each command line argument given to program would additionally be individually quoted (you generally want this). program () { "$GOBIN"/program "$@" } You would then call program...
How to pass all arguments of a function along to another command?
1,512,259,936,000
Problem: I have multiple bash functions and aliases. I can't remember all of them off the top of my head, so I usually end up opening my .bash_functions and .bash_aliases files to find what I need. Question(s): How can I list functions/aliases available from the bash prompt? Is it possible for me to document my bash f...
To list active aliases, run: alias To see names of all active functions, run: declare -F To see the names and definitions of all active functions, run: declare -f More The information on aliases is also available is a script-friendly format with: declare -p BASH_ALIASES man bash provides more info on the alias bui...
How to document my custom bash functions and aliases?
1,512,259,936,000
I have the following function: bar() { echo $1:$2; } I am calling this function from another function, foo. foo itself is called as follows: foo "This is" a test I want to get the following output: This is:a That is, the arguments that bar receives should be the same tokens that I pass into foo. How does foo need t...
Use "$@": $ bar() { echo "$1:$2"; } $ foo() { bar "$@"; } $ foo "This is" a test This is:a "$@" and "$*" have special meanings: "$@" expands to multiple words without performing expansions for the words (like "$1" "$2" ...). "$*" joins positional parameters with the first character in IFS (or space if IFS is unset o...
Pass arguments to function exactly as-is
1,512,259,936,000
How can I write a function in zsh that invokes an existing command with the same name as the function itself? For example, I've tried this to illustrate my question: function ls { ls -l $1 $2 $3 } When I execute it with ls * I get the following: ls:1: maximum nested function level reached I assume this is becau...
What is happening is that you are recursively calling your ls function. In order to use the binary, you can use ZSH's command builtin. function ls { command ls -l "$@" }
How can I create a function in zsh that calls an existing command with the same name?
1,512,259,936,000
The following variables are used to get the positional parameters: $1, $2, $3, etc. $@ $# But they are used for both positional parameters of the script and the positional parameters of a function. When I use these variables inside a function, they give me the positional parameters of the function. Is there a way to ...
No, not directly, since the function parameters mask them. But in Bash or ksh, you could just assign the script's arguments to a separate array, and use that. #!/bin/bash ARGV=("$@") foo() { echo "number of args: ${#ARGV[@]}" echo "second arg: ${ARGV[1]}" } foo x y z Note that the numbering for the array s...
Is there a way to get the positional parameters of the script from inside a function in bash?
1,512,259,936,000
I was discussing with my friend on how the commands are parsed in the shell, and he told me that bash searches the command in following order List of aliases List of shell keywords List of user defined functions List of shell built in functions List of directories specified in the PATH variable , from left...
In Bash: man bash | grep -10 RESERVED lists reserved words: ! case coproc do done elif else esac fi for function if in select then until while { } time [[ ]] declare -F and typeset -F shows function names without their contents. enable lists builtin shell commands (I don't think these are functions as such).So doe...
What are commands to find shell keywords, built in functions and user defined functions?
1,512,259,936,000
I have declared functions and variables in bash/ksh and I need to forward them into sudo su - {user} << EOF: #!/bin/bash log_f() { echo "LOG line: $@" } extVAR="yourName" sudo su - <user> << EOF intVAR=$(date) log_f ${intVAR} ${extVAR} EOF
sudo su -, which is a complicated way of writing sudo -i, constructs a pristine environment. That's the point of a login shell. Even a plain sudo removes most variables from the environment. Furthermore sudo is an external command; there's no way to elevate privileges in the shell script itself, only to run an externa...
Forward function and variables into sudo su - <user> <<EOF
1,512,259,936,000
Solaris / sh I have a few functions defined in a file which gets loaded via . ./some_file.sh When I start a subshell with sh All my function definitions are lost but when I do env I do see the source, is there an easy way to get them functional in my subshell?
Functions are naturally propagated to subshells: greet () { echo "hello, $1" } ( echo "this is a subshell"; greet bob ) But they are not and cannot be propagated to independent shell processes that you start by invoking the shell under its name. Bash has an extension to pass functions through the environment, but t...
How to get functions propagated to subshell?
1,512,259,936,000
I often generate and register a lot of bash functions that automate many of the task I usually do in my development projects. That generation depends on the meta-data of the project I am working on. I want to annotate the functions with the info of the project they were generated, this way: func1() { # This function ...
function func_name() { : ' Invocation: func_name $1 $2 ... $n Function: Display the values of the supplied arguments, in double quotes. Exit status: func_name always returns with exit status 0. ' : local i echo "func_name: $# arguments" for ((i = 1; i <= $#; ++i)); do echo "func_name [$i] \"...
assign and inspect bash function metadata
1,512,259,936,000
I have a function in my .bashrc file. I know what it does, it steps up X many directories with cd Here it is: up() { local d="" limit=$1 for ((i=1 ; i <= limit ; i++)) do d=$d/.. done d=$(echo $d | sed 's/^\///') if [ -z "$d" ]; then d=.. fi cd $d } But can you ex...
d=$d/.. adds /.. to the current contents of the d variable. d starts off empty, then the first iteration makes it /.., the second /../.. etc. sed 's/^\///' drops the first /, so /../.. becomes ../.. (this can be done using a parameter expansion, d=${d#/}). d=.. only makes sense in the context of its condition: if [ -...
Can you explain these three things in this bash code for me?
1,512,259,936,000
I'm trying to execute the code below but when I try to use my function in the if statement I get the -bash: [: too many arguments error. Why is it happening? Thank you in advance! notContainsElement () { local e match="$1" shift for e; do [[ "$e" == "$match" ]] && return 1; done return 0 } list=( "pears" "app...
When using if [ ... ] you are actually using the [ utility (which is the same as test but requires that the last argument is ]). [ does not understand to run your function, it expects strings. Fortunately, you don't need to use [ at all here (for the function at least): if [ "$docheck" -eq 1 ] && notContainsElement "...
Shell: Using function with parameters in if
1,512,259,936,000
Let's say that I have a command git branch (always with a couple of words) for example. What I want is to keep track of when this command is executed with arguments. For example, if I execute the command git branch develop without errors, I want to save develop on a file. I tried to overwrite git command on my .bash_p...
You've got a few problems here: your git function is calling itself recursively instead of the original git command. you're using $@ unquoted which doesn't make any sense whatsoever you're leaving other variables unquoted, asking the shell to split+glob them. you're using echo for arbitrary data. you're losing the ex...
Track certain parameters on some command
1,512,259,936,000
I am using zsh and I have defined few utility shell function in some shell scripts, few of them called from ~/.zshrc, so let's assume that we don't know the location of these functions. One function is: function k.pstree.n { if [ "$1" != "" ] then pstree -p | grep -C3 "$1" else printf " Pl...
There is built-in command functions in zsh for this purpose functions k.pstree.n For example in case of my preexec function: $ functions preexec preexec () { local cmd=${1:-} cmd=${cmd//\\/\\\\} [[ "$TERM" =~ screen* ]] && cmd="S $cmd" inf=$(print -Pn "%n@%m: %3~") print -n "\e]2;$cmd $inf\a" ...
How do you print the code of a shell function in terminal?
1,512,259,936,000
I would like to slightly extend a zsh completion function. I would like to avoid putting the complete function body into my homedir with only one line changed. Instead I would like to intercept it's call and then call the original function myself. In quasi code: <make sure _the_original_function is loaded> _backup_of_...
How to patch a function The code of a function is stored in the associative array functions. That's the source code with normalized whitespace and no comments (zsh has done lexical analysis and pretty-prints the tokens). You can change the code of a function by modifying the entry of the functions array. For example, ...
overwrite and reuse existing function in zsh
1,512,259,936,000
(This is on MacOS with zsh 5.7.1) Here is how I load custom functions in zsh: # Custom functions fpath=($HOME/.zfunc $fpath) autoload -Uz mackupbackup autoload -Uz tac autoload -Uz airplane autoload -Uz wakeMyDesktop Each function is its own file in the ~/.zfunc directory. Note this directory is symlinked into a diff...
Sourcing an rc file rarely if ever works in practice, because people rarely write them to be idempotent. A case in point is your own, where you are prepending the same directory to the fpath path every time, which of course means that searching that path takes a little longer each time. No doubt this isn't the only ...
zsh: `source` command doesn't reload functions
1,512,259,936,000
I have been slowly migrating from Bash to Zsh and have got to the point where everything I have moved across is working well, with one exception. I have a couple of functions in my .bashrc that I use dozens of times a day and two of them do not work under Zsh. The three functions comprise a basic note taking facility....
local is a builtin, not a keyword, so local files=(…) isn't parsed as an array assignment but as a string assignment. Write the assignment separately from the declaration. (Already found by llua, but note that you need to initialize files to the empty array or declare the variable with typeset -a, otherwise the array...
Bash function not working in Zsh
1,512,259,936,000
What is the difference between autoload -U and plain autoload? For instance, here it is recommended to run: autoload -U run-help autoload run-help-git autoload run-help-svn autoload run-help-svk unalias run-help alias help=run-help Why is -U only in the first line?
Yes, you do see the recommendation for -U often, usually paired with -z. It’s not documented in the run-help for autoload, but there is a section titled “AUTOLOADING FUNCTIONS” in the manpage for zshmisc. There it states: The usual alias expansion during reading will be suppressed if the autoload builtin or its ...
What is the difference between `autoload` and `autoload -U` in Zsh?
1,512,259,936,000
Stuck with GNU awk 3.1.6 and think I've worked around its array bugs but still have what looks like a scope problem in a 600-line awk program. Need to verify understanding of array scope in awk to find my bug. Given this illustrative awk code... function foo(ga) { ga[1] = "global result" } garray[1] = "global" foo(...
Function parameters are local to the function. awk ' function foo(x,y) {y=x*x; print "y in function: "y} BEGIN {foo(2); print "y out of function: " y} ' y in function: 4 y out of function: If you pass fewer values to a function than there are parameters, the extra parameters are just empty. You might somet...
Gawk: Passing arrays to functions
1,512,259,936,000
WARNING - this question is about the Bash before the shellshock vulnerability, due to which it was changed. I have seen something like this in my bash ENV: module=() { eval `/usr/bin/modulecmd bash $*` } How does this construct work? What is it called? I'm not asking about modulecmd, I am asking about the entire ...
It's really a function named module. It appears in environment variables when you export a function. $ test() { echo test; } $ export -f test $ env | sed -n '/test/{N;p}' test=() { echo test } From bash documentation - export: export export [-fn] [-p] [name[=value]] Mark each name to be passed to child processes ...
How does VARIABLE=() { function definition } work in bash
1,512,259,936,000
I have a number of functions defined in my .bashrc, intented to be used interactively in a terminal. I generally preceded them with a comment describing its intended usage: # Usage: foo [bar] # Foo's a bar into a baz foo() { ... } This is fine if browsing the source code, but it's nice to run type in the terminal ...
I don't think that there is just one good way to do this. Many functions, scripts, and other executables provide a help message if the user provides -h or --help as an option: $ foo() { [[ "$1" =~ (-h|--help) ]] && { cat <<EOF Usage: foo [bar] Foo's a bar into a baz EOF return; } : ...other stuff... } For example: $ ...
Displaying usage comments in functions intended to be used interactively
1,512,259,936,000
I wanted to search for the string '.vars()' in all my Python files, and somehow I redefined 'grep' as follows: % grep .vars() *.py % which grep grep () { *.py } I have tried using unset grep and export grep=/bin/grep to correct this, without success. Can so...
This is a function definition. More precisely, this is the definition of two functions with the same code. It looks unusual because zsh has several extensions to the basic syntax of function definitions name () { instruction; … }: Zsh allows multiple names. name1 name2 () { instruction; … } defines both the functions...
How to undefine a zsh command created accidentally?
1,512,259,936,000
I am trying to pass a "var name" to a function, have the function transform the value the variable with such "var name" contains and then be able to reference the transformed object by its original "var name". For example, let's say I have a function that converts a delimited list into an array and I have a delimited ...
Description Understanding this will take some effort. Be patient. The solution will work correctly in bash. Some "bashims" are needed. First: We need to use the "Indirect" access to a variable ${!variable}. If $variable contains the string animal_name, the "Parameter Expansion": ${!variable} will expand to the content...
How to use call-by-reference on an argument in a bash function
1,512,259,936,000
I just decided to try zsh (through oh-my-zsh), and am now playing with precmd to emulate a two-line prompt that has right prompts in more than just the last line. So I clone the default theme, and inspired by this post (that I'm using to learn a lot too), i do somehting like this (I'll add colors later): function prec...
Zsh doesn't have anything like closures or packages or namespaces. Zsh lacks a bunch of things required to have true closures: Functions aren't first class. You can't pass functions around as arguments to other functions, and functions can't return other functions. (You can pass the name of a function to call, but th...
Is there something like closures for zsh?
1,512,259,936,000
Is it possible to treat a block of commands as an anonymous function? function wrap_this { run_something # Decide to run block or maybe not. run_something else } wrap_this { do_something do_somthing else } # Do something else wrap_this { do_something_else_else do_something_else_else_else } (I ...
This is the shortest solution that I could think of: Given these functions: # List processing map() { while IFS='' read -r x; do "$@" "$x"; done; } filter() { while IFS='' read -r x; do "$@" "$x" >&2 && echo "$x"; done; } foldr() { local f="$1"; local result="$2"; shift 2; while IFS='' read -r x; do result="$( "$f" "...
Passing a code block as an anon. function
1,512,259,936,000
I wrote a function in Bash to see man pages in Vim: viman () { man "$@" | vim -R +":set ft=man" - ; } This works fine, the only problem occurs if I pass a man page to it which doesn't exist. It prints that the man page doesn't exist but still opens vim with an empty buffer. So, I changed the function to check the err...
Try this: capture the man output, and if successful launch vim viman () { text=$(man "$@") && echo "$text" | vim -R +":set ft=man" - ; }
Viewing man pages in Vim
1,512,259,936,000
I'm writing a zsh shell function (as opposed to a script) where I would really like the extended_glob option to be enabled. But since the function runs in the caller's context, I don't want to clobber their settings. What I'd like to do is conditionally enabled extended_glob as long as I need it and then restore it to...
You can use the local_options option to automatically restore options when the function exits. This would only be appropriate if your function does not make any other option changes that you intend to persist after the function has finished. Thus, you could write your function like this: do_something() { setopt loca...
Restoring an option at the end of a function in zsh
1,512,259,936,000
In bash, sometimes I would like to reuse a function in several scripts. Is it bad to repeat the definition of the function in all the scripts? If so, what is some good practice? Is the following way a good idea? wrap the definition of a function myfunction in its own script define_myfunction.sh, in any script where ...
In bash, that is a good way of doing it, yes. Sourcing the "library" script using source or . would be an adequate solution to your issue of wanting to share a function definition between two or more scripts. Each script that needed access to the function(s) defined in the "library" script(s) would source the needed f...
How shall I reuse a function in multiple scripts?
1,512,259,936,000
The shellshock bug in bash works by way of environment variables. Honestly I was suprised by the fact that there is such a feature like: "passing on of function definitions via env vars" Therefore this question while maybe not perfectly formulated is to ask for an example or a case in which it would be necessary to h...
When a script invokes another script, variables of the parent script can be exported, and then they'll be visible in the child script. Exporting functions is an obvious generalization: export the function from the parent, make it visible in the child. The environment is the only convenient way a process can pass arbit...
Why does bash even parse/run stuff put in the environment variable?
1,512,259,936,000
I want to write a function that checks if a given variable, say, var, starts with any of the words in a given list of strings. This list won't change. To instantiate, let's pretend that I want to check if var starts with aa, abc or 3@3. Moreover, I want to check if var contains the character >. Let's say this function...
check_prefixes () { value=$1 for prefix in aa abc 3@3; do case $value in "$prefix"*) return 0 esac done return 1 } check_contains_gt () { value=$1 case $value in *">"*) return 0 esac return 1 } var='aa>' if check_prefixes "$var" && check_contain...
Write a function that checks if a string starts with or contains something
1,512,259,936,000
I'm trying to create a function and believe I found a good working example but I don't understand all the logic behind it. More specifically, on the "while" line, could someone explain what test is and does? what is $# (isn't # a comment char?) and were does the -gt 0 parameter comes from? couldn't find it in the whil...
While # on it's own is definitely a comment, $# contains the number of parameters passed to your function. test is an program which lets you perform various tests, for example, if one number is greater than another number (if your operator is -gt; there are many other operators, see man test). It will return success i...
What does "while test $# -gt 0" do?
1,512,259,936,000
To make it short, doing something like: -bash$ function tt { echo $0; } -bash$ tt $0 will return -bash, but how to get the function name called, i.e. tt in this example instead?
In bash, use FUNCNAME array: tt() { printf '%s\n' "$FUNCNAME" } With some ksh implementations: tt() { printf '%s\n' "$0"; } In ksh93: tt() { printf '%s\n' "${.sh.fun}"; } From ksh93d and above, you can also use $0 inside function to get the function name, but you must define function using function name { ...; }...
How to determine callee function name in a script
1,512,259,936,000
I have this function, rpargs () { local i args=() for i in "$@" do test -e "$i" && args+="$(realpath --canonicalize-existing -- "$i")" || args+="$i" done } And I want to return args. The only ways I can think of are either to printf '%s\0' and then split it via expansion flags (0@), or to...
zsh's return builtin can only return a 32bit signed integer like the _exit() system call. While that's better than most other Bourne-like shells, that still can't return arbitrary strings or list of strings like the rc/es shells. The return status is more about returning a success/failure indication. Here, alternative...
What's the idiomatic way of returning an array in a zsh function?
1,512,259,936,000
Consider this script: function alfa(bravo, charlie) { if (charlie) return "charlie good" else { return "charlie bad" } } BEGIN { print alfa(1, 1) print alfa(1, 0) print alfa(1, "") print alfa(1) } Result: charlie good charlie bad charlie bad charlie bad Does Awk have a way to tell when an argum...
Yes, you can do this: function alfa(bravo, charlie) { if (charlie) { return "charlie good" } if (charlie == 0 && charlie == "") { return "charlie not provided" } if (!charlie && charlie != 0) { return "charlie null" } if (!charlie && charlie != "") { return "charlie 0" } } Result: ch...
Detect optional function argument (scalar)
1,512,259,936,000
I'm dabbling in traps in Bash again. I've just noticed the RETURN trap doesn't fire up for functions. $ trap 'echo ok' RETURN $ f () { echo ko; } $ f ko $ . x ok $ cat x $ As you can see it goes off as expected for sourcing the empty file x. Bash's man has it so: If a sigspec is RETURN, the command arg is executed ...
As I understand this, there's an exception to the doc snippet in my question. The snippet was: If a sigspec is RETURN, the command arg is executed each time a shell function or a script executed with the . or source builtins finishes executing. The exception is described here: All other aspects of the shell exe...
RETURN trap in Bash not executing for function
1,512,259,936,000
I know that set -e is my friend in order to exit on error. But what to do if the script is sourced, e.g. a function is executed from console? I don't want to get the console closed on error, I just want to stop the script and display the error-message. Do I need to check the $? of each command by hand to make that pos...
I would recommend having one script that you run as a sub-shell, possibly sourcing a file to read in function definitions. Let that script set the errexit shell option for itself. When you use source from the command line, "the script" is effectively your interactive shell. Exiting means terminating the shell session...
Return on error in shellscript instead of exit on error
1,512,259,936,000
How can one measure individual calls to bash functions from inside the bash file. I have a program that I call using the command eclipse -b col_solve.pl -e "myPred" This call outputs some information, the last of which is SUCCESS or FAIL. I am writing a script that is called on a bunch of files in a directory, and ...
Use the time keyword instead of the external command. Using the keyword allows you to run time on any shell command, including function calls, not just on running a program. You can control the output format to some extent through the TIMEFORMAT variable. TIMEFORMAT=%2U time run_eclipse_on … echo "$i::$stat" The time...
Using time on bash functions (not commands)
1,512,259,936,000
Here's a simplified version of my script. My question is, How do I return the exit code from apt-get in this case? #!/bin/bash install_auto() { apt-get -h > /dev/null 2>&1 if [ $? -eq 0 ] ; then return $(sudo apt-get install --assume-yes $@) fi return 1 } echo "installing $@" install_auto "$@" echo $? echo "finish...
Bash's return() can only return numerical arguments. In any case, by default, it will return the exit status of the last command run. So, all you really need is: #!/usr/bin/env bash install_auto() { apt-get -h > /dev/null 2>&1 if [ $? -eq 0 ] ; then sudo apt-get install --assume-yes $@ fi } You don't need to expl...
How to return the exit code? Error: return: Reading: numeric argument required
1,512,259,936,000
I'm trying to source a file whose name is passed from stdin. My plan is to create a function like this: mySource() { # get stdin and pass it as an argument to `source` source $(cat) } to be called like this: $ echo "file1.sh" | mySource wherein file1.sh is: FILE=success export FILE Assuming $FILE is initiali...
You can change your mySource function to: mySource() { source "$1" } Then calling it with: $ mySource file.sh $ printf '%s\n' "$FILE" success You can also make mySource handles multiple files: mySource() { for f do source "$f" done }
Calling `source` from bash function
1,512,259,936,000
Suppose I have bash_functions.sh: function test(){ } function test2(){ } And in my ~/.bashrc I do: source ~/bash_functions.sh Is it possible to, when sourcing it, avoid sourcing a specific function? I mean, source everything in bash_functions.sh, except for test?
In a function definition foo () { … }, if foo is an alias, it is expanded. This can sometimes be a problem, but here it helps. Alias foo to some other name before sourcing the file, and you'll be defining a different function. In bash, alias expansion is off by default in non-interactive shells, so you need to turn it...
Is it possible to source a file in bash, but skipping specific functions?
1,512,259,936,000
I'm writing a set of shell functions that I want to have working in both Bash and KornShell93, but with Bash I'm running into a "circular name reference" warning. This is the essence of the problem: function set_it { typeset -n var="$1" var="hello:$var" } function call_it { typeset -n var="$1" set_i...
Chet Ramey (Bash maintainer) says There was extensive discussion about namerefs on bug-bash earlier this year. I have a reasonable suggestion about how to change this behavior, and I will be looking at it after bash-4.4 is released. In the meanwhile, I'm resorting to slightly obfuscate the names of my local nam...
Circular name references in bash shell function, but not in ksh
1,512,259,936,000
In zsh I am using the following function to delete a local and a remote branch with one command: gpDo () { git branch -d "$1" && git push --delete origin "$1" } Currently, auto-completion for the Git branch does not work. I have to manually type the whole branch name. How can I get tab completion working for such...
I assume you're using the “new” completion system enabled by compinit. If you're using oh-my-zsh, you are. You need to tell zsh to use git branch names for gpDo. Git already comes with a way to complete branch names. As of zsh 5.0.7 this is the function __git_branch_names but this isn't a stable interface so it could ...
zsh: Tab completion for function with Git commands
1,512,259,936,000
I'm customizing my zsh PROMPT and calling a function that may or may not echo a string based on the state of an environment variable: function my_info { [[ -n "$ENV_VAR"]] && echo "Some useful information\n" } local my_info='$(my_info)' PROMPT="${my_info}My awesome prompt $>" I would like the info to end on a t...
Final newlines are removed from command substitutions. Even zsh doesn't provide an option to avoid this. So if you want to preserve final newlines, you need to arrange for them not to be final newlines. The easiest way to do this is to print an extra character (other than a newline) after the data that you want to obt...
Elegant way to prevent command substitution from removing trailing newline
1,512,259,936,000
I have 3 functions, like function WatchDog { sleep 1 #something } function TempControl { sleep 480 #somthing } function GPUcontrol { sleep 480 #somethimg } And i am runing it like WatchDog | TempControl | GPUcontrol This script is in rc.local file. So, logically it should run at automatically. The thing is that ...
Pipe sends the output of one command to the next. You are looking for the & (ampersand). This forks processes and runs them in the background. So if you ran: WatchDog & TempControl & GPUcontrol It should run all three simultaneously. Also when you run sudo bash /etc/rc.local I believe that is running them in serie...
Parallel running of functions
1,512,259,936,000
I am aware that aliases can be bypassed by quoting the command itself. However, it seems that if builtin commands are "shadowed" by functions with the same names, there is no way to execute the underlying builtin command except...by using a builtin command. If you can get to it. To quote the bash man page (at LESS='+...
When bash is in posix mode, some builtins are considered special, which is compliant with POSIX standard. One special thing about those special builtins, they are found before function in command lookup process. Taking this advantage, you can try: $ unset builtin Haha, nice try! builtin $ set -o posix $ unset builtin ...
How to bypass bash functions called `command`, `builtin` and `unset`?
1,497,561,233,000
Notice that we return from a loop, which is redirected. I don't know, if I should worry about the write buffer of "file". function f { i=1 while : do echo aaaaaaaaaaaaabbbbbbbbbbbbbbbbb ((i++)) if [ $i -gt 3 ] then return # return while redirected fi ...
While each command may have its own write buffer, there is no write buffer that is shared between commands even built-in in bash (or even two invocations of a same command, built-in or not). Even ksh93 which has been known to do some I/O optimisation (for instance, it will read-ahead and share some data on input (caus...
bash, return from redirected loop, is it safe?
1,497,561,233,000
I can grep the output of jobs, and I can grep the output of a function. But why can't I grep the output of jobs when it's in a function? $ # yes, i can grep jobs $ jobs [1]+ Running vim [2]+ Stopped matlab $ jobs | grep vim [1]+ Running vim $ # yes, of course i can grep a function $ typ...
Eric Blake answered on the bash-bugs mailing list: jobs is an interesting builtin - the set of jobs in a parent shell is DIFFERENT than the set of jobs in a subshell. Bash normally creates a subshell in order to do a pipeline, and since there are no jobs in that subshell, the hidden execution of jobs has nothi...
Cannot grep jobs list when jobs called in a function
1,497,561,233,000
How can I check if a command is a built-in command for ksh? In tcsh you can use where; in zsh and bash you can use type -a; and in some modern versions of ksh you can use whence -av. What I want to do is write an isbuiltin function that works in any version of ksh (including ksh88 and any other "old" versions of ksh) ...
If your concern is about aliases, just do: [[ $(unalias -- "$cmd"; type -- "$cmd") = *builtin ]] ($(...) create a subshell environment, so unalias is only in effect there). If you're also concerned about functions, also run command unset -f -- "$cmd" before type.
Checking if a command is a built-in in ksh
1,497,561,233,000
I have a BASH script that calls a function, which calls other functions: #!/bin/bash function foo { function bar { # do something } bar } foo How can I return from bar directly to the main function? The case is that bar handles user input and if it receives a negative answer, it must return to...
There is no nice way (I am aware of) to do that but if you are willing to pay the price... Instead of putting the code in functions you can put it in files you source. If the functions need arguments then you have to prepare them with set: set -- arg1 arg2 arg3 source ... Three files: testscript.sh #! /bin/bash sta...
BASH return to main function
1,497,561,233,000
I've got 'color cat' working nicely, thanks to others (see How can i colorize cat output including unknown filetypes in b&w?). In my .bashrc: cdc() { for fn in "$@"; do source-highlight --out-format=esc -o STDOUT -i $fn 2>/dev/null || /bin/cat $fn; done } alias cat='cdc' # To be next to the cdc definition above....
Something like this should do what you want: for cmd in cat head tail; do cmdLoc=$(type $cmd | awk '{print $3}') eval " $cmd() { for fn in \"\$@\"; do source-highlight --failsafe --out-format=esc -o STDOUT -i \"\$fn\" | $cmdLoc - done } " done You can condense it lik...
How can I colorize head, tail and less, same as I've done with cat?
1,497,561,233,000
I'm trying to figure out how to make a function that can take an array as a parameter and sort it. I think it is done with positional variables, but I'm not sure.
Sort the easy way with sort, tr: arr=($(for i in {0..9}; do echo $((RANDOM%100)); done)) echo ${arr[*]}| tr " " "\n" | sort -n | tr "\n" " " Into a new array: arr2=($(echo ${arr[*]}| tr " " "\n" | sort -n)) Without help by tr/sort, for example bubblesort: #!/bin/bash sort () { for ((i=0; i <= $((${#arr[@]}...
How to create a function that can sort an array in bash?
1,497,561,233,000
I'm trying to define a bash function dynamically using following code: delegate_function() { echo "output from delegate"; } eval "parent_function() { echo $(delegate_function); }" The intent is to have parent function dynamically dispatch to the delegate when executed. However due to the way eval works my function is...
Escaping $ should be enough to make this work: eval "parent_function() { echo \$(delegate_function); }"
Defining bash function dynamically using eval
1,497,561,233,000
I create a script, paste data in it, saving, executing, and delete: vi ~/ms.sh && chmod +x ~/ms.sh && nohup ~/ms.sh && rm ~/ms.sh #!/bin/bash commands... function myFunc { commands... } myFunc () How could I properly run only myFunc, in the background, or alternatively, in another process? If it's even possible...
You can use a shell function pretty much anywhere you can use a program. Just remember that shell functions don't exist outside the scope in which they were created. #!/bin/bash # f() { sleep 1 echo "f: Hello from f() with args($*)" >&2 sleep 1 echo "f: Goodbye from f()" >&2 } echo "Running f() in the...
How to run a function in background?
1,497,561,233,000
I'm trying make a function that simplifies grepping a log I have to work with on a regular basis. I'd like to use extended regexp with it pipe and redirect the output, etc. But I'm having trouble doing this using the standard grep pattern file syntax in the function. The way I have it set up now is horrible to look at...
The following code has $args quoted: grep "$args" /path/to/logs/my.log This asks to pass the entire value of that variable as a single parameter to grep. Thus, if you call mygrep with parameters -i and -E, grep will in fact receive a single parameter -i -E, which is indeed invalid. The following should do it: functio...
Function to simplify grep with an often used log
1,497,561,233,000
When I execute the following script #!/usr/bin/env bash main() { shopt -s expand_aliases alias Hi='echo "Hi from alias"' Hi # Should Execute the alias \Hi # Should Execute the function "Hi" } function Hi() { echo "Hi from function" } main "$@" Very first time it executes the function and t...
Alias expansion in a function is done when the function is read, not when the function is executed. The alias definition in the function is executed when the function is executed. See Alias and functions and https://www.gnu.org/software/bash/manual/html_node/Aliases.html This means, the alias will be defined when func...
Unexpected behavior of Bash script: First executes function, afterwards executes alias
1,497,561,233,000
I'm looking for something similar to Bash's built-in command that will only run something if it is a function. So currently I have an insecure way of doing: # Go through arguments in order for i in $*; do if [ -z `which $i` ]; then # Run function $i && echo -n ' ' fi done This if statement doe...
With bash, you can do something like this: for f do if declare -F -- "$f" >/dev/null 2>&1; then : "$f" is a function, do something with it fi done declare -F -- "$f" >/dev/null 2>&1 will return success code if $f is a bash function, output nothing. You might also want to disable some special builtin commands ...
Execute only if it is a bash function
1,497,561,233,000
I'm new to bash functions but was just starting to write some bits and pieces to speed up my work flow. I like to test this as I go along so I've found myself editing and sourcing my ~/.profile a lot and find ~/. a bit awkward to type... So the first thing I thought I'd do was the following: sourceProfile(){ sour...
Aliases are like some form of macro expansion, similar to the pre-preprocessing done in C with #define except that in shells, there's no clear and obvious delimitation between the pre-processing stage and the interpretation stage (also, aliases are not expanded in all contexts and there can be several rounds of alias ...
Bash functions, something strange going on!
1,497,561,233,000
In my .bash_aliases I have defined a function that I use from the command line like this: search -n .cs -n .cshtml -n .html SomeTextIWantToSearchFor /c/code/website/ /c/stuff/something/whatever/ The function builds a grep command that pipes the result to another grep command (unfortunately convoluted because I am stu...
Your problem is the second grep: ... | grep "$file_names" When you call your function, the space between the -n and the file name (-n page1.cshtml) is included in the $file_names array. Then, the substitution: file_names=${file_names// /':\|'}: Will add an extra :\| at the beginning of the string because of the lead...
Function that calls another function with list of arguments doesn't work
1,497,561,233,000
I want to know what return values we can use that will not be mistaken by for ex. SIGINT? ex.: $sleep 10 $#hit ctrl+c $echo $? 130 so I know I must not use anything like return 130 or exit 130 so this would be misleading: $function FUNC(){ return 130; };FUNC;echo $? 130
You can use any number between 0 to 255 except for reserved exit codes (click here to know more)
What return/exit values can I use in bash functions/scripts?
1,497,561,233,000
How can I get this script file's functions to load without having to source it every time? I created a file foo with script functions I'd like to run. It's in /usr/bin, which is in the PATH. File foo: #!/bin/bash echo "Running foo" function x { echo "x" } However, when I type a function name like x in the termin...
mikeserv's answer is good for the details of what goes on "behind the scenes", but I feel another answer here is warranted as it doesn't contain a simple usable answer to the exact title question: How can I get this script file's functions to load without having to source it every time? The answer is: Source it from...
How can I get this script file's functions to load without having to source it every time? "command not found" (Bash/scripting basics)
1,497,561,233,000
I have written one simple function in shell that returns 0 or 1 based on some condition.Let me call that function name foo foo(){ ... ... } Now i am trying to call foo in if condition as follow:- if ( foo $1 ) ... .. It works fine.But when i used follow approach to call ,then i get error if [ foo $1 ] ... ......
When you use: if ( foo $1 ) You are simple executing foo $1 in a subshell and if is acting on it's exit status. When you use: if [ foo $1 ] You are attempting to use the shell test and foo is not a valid test operator. You can find the valid test operators here. It's not necessarily relevant for your issue but you...
Calling function in Shell script
1,497,561,233,000
If you call the command help declare. You will see the following information: -t NAME : to make NAMEs have the `trace' attribute Is there any example that demonstrates the use of this option. I thought that this plays the same role as that of the command set -o functrace except that it only applies to the arguments ...
declare -t foo sets the trace attribute on the variable foo (which has no special effect anyway). You need to use -f to set it on the function: declare -ft foo With your script modified to use -f, I get the following output (explanation in comments): var is 0 # foo called var is 0 # before the first command in functi...
What is the use of declare with option -t
1,497,561,233,000
Here is a simplified code that prints the name of Directory if it contains a Filename with same name as the parent directory and .md extension. FIND(){ find . -type d -exec sh -c ' for d do [ -f "${d}/${d##*/}.md" ] && printf "%s\n" "$d" done' find-sh {} + } FIND To generalize I want...
The in-line script that you call is single-quoted (as it should be). This means that the sh -c shell will get a script where "${SearchTerm}" is unexpanded. Since that shell does not have a SearchTerm variable, its value will be empty. Since you tagged your question with bash, you can pass the name of an exported func...
Find exec sh: Shell variable not getting passed to subshell
1,497,561,233,000
I want to execute a Bash function at a scheduled time. I think the right tool for this is the at command. However, it doesn't seem to be working. function stupid () { date } export -f stupid cat << EOM | at now + 1 minute stupid EOM After waiting the minute, I check my mail and this is the error I see: sh: line...
Bash functions are exported via the environment. The at command makes the environment, the umask and the current directory of the calling process available to the script by generating shell code that reproduces the environment. The script executed by your at job is something like this: #!/bin/bash umask 022 cd /home/n...
Can you execute a Bash function with the `at` command?