date int64 1,220B 1,719B | question_description stringlengths 28 29.9k | accepted_answer stringlengths 12 26.4k | question_title stringlengths 14 159 |
|---|---|---|---|
1,497,561,233,000 |
I found a Bash script snippet earlier with which to echo a string to stderr:
echoerr() { echo "$@" 1>&2; }
echoerr hello world
This remained in my clipboard, and when I wanted to edit a file (with VIM) I accidentally pasted this snippet again instead of the file name:
vim echoerr() { echo "$@" 1>&2; }
echoerr hello w... |
Because zsh allows you to define function with multiple names. From man zshmisc:
function word ... [ () ] [ term ] { list }
word ... () [ term ] { list }
word ... () [ term ] command
where term is one or more newline or ;. Define a function which
is referenced by any one of w... | Command re-assigned |
1,497,561,233,000 |
I love using the following pattern for searching in files:
grep --color=auto -iRnHr --include={*.js,*.html,} --exclude-dir={release,dev,} "span" .
I'd like, however, to have this one wrapped into a bash command like this:
findinfiles {*.js,*.html,} {release,dev,} "span" // syntax is just a guessing
I cannot solve t... |
When you run findinfiles {*.js,*.html,} {release,dev,} "span", here is what happens:
Bash parses quotes and splits the command into words: findinfiles, {*.js,*.html,} {release,dev,} span.
Bash expands the braces, resulting in the list of words findinfiles, *.js, *.html, release, dev, span.
Bash expands the wildcard p... | Bash: passing braces as arguments to bash function |
1,497,561,233,000 |
In a bash script I have a log() function that is used in several places, as well as a logs() function that diverts lots of line to log(). When I run parts of the script with set -x, obviously all commands within logs() and log() are traced too.
I would like to define logs() and log() such that at least their content, ... |
A quick and dirty hack that should work in all shells is to (temporarily) make your log an external script instead of a function.
In bash you could also use a trap '...' DEBUG and shopt -s extdebug combination, which is much more versatile than set -x. Example:
debug() {
local f=${FUNCNAME[1]} d=${#FUNCNAME[@]... | Define bash function which does not show up in xtrace (set -x) |
1,497,561,233,000 |
I want to write my Bash functions each in a separate file, for easier version control, and source the whole lot of them in my .bashrc.
Is there a more robust way than e.g.:
. ~/.bash_functions/*.sh
|
It's simply a matter of surrounding it all with appropriate error checks:
fn_dir=~/.bash_functions
if [ -d "$fn_dir" ]; then
for file in "$fn_dir"/*; do
[ -r "$file" ] && . "$file"
done
fi
| How can I source several files into my .bashrc? |
1,497,561,233,000 |
See the code below:
a()(alias x=echo\ hi;type x;alias;x);a
I have an alias inside a function, I do not want to change the external environment (that is why I am using () instead of {}), even the code saying the alias was successfully setted, it does not work, check the output out:
x is aliased to `echo hi'
...
alias... |
If you're not averse to using eval:
$ busybox ash -c 'a()(alias x=echo\ hi;type x;alias;eval x);a'
x is an alias for echo hi
x='echo hi'
hi
I have no idea why this works.
| Why alias inside function does not work? [duplicate] |
1,497,561,233,000 |
I received a great function for highlighting files in Apple's finder using the command-line. It's basically a wrapper for osascript.
I got it from Mac OS X: How to change the color label of files from the Terminal and it looks like this,
# Set Finder label color
label(){
if [ $# -lt 2 ]; then
echo "USAGE: label ... |
To call label with xargs you could try something like this:
export -f label
find /Users/brett/Development/repos/my-repo/ -name "*.php" -print0 |
xargs -0 grep -Iil 'mysql_query(' |
xargs -I {} -n 1 bash -c 'label 2 {}'
Note how label 2 {} in the latter xargs call has been changed to bash -c 'label 2 {}'. As xargs... | Can you pipe to a .bash_profile function? |
1,497,561,233,000 |
Bash can print a function defintion:
$ bash -c 'y(){ echo z; }; export -f y; export -f'
y ()
{
echo z
}
declare -fx y
However this fails under POSIX Bash, /bin/sh and /bin/dash:
$ bash --posix -c 'y(){ echo z; }; export -f y; export -f'
export -f y
Can a function definition be printed under a POSIX shell?
|
You can not do it portably. POSIX spec did not specify any way to dump function definition, nor how functions are implemented.
In bash, you don't have to export the function to the environment, you can use:
declare -f funcname
(Work in zsh)
This works even you run bash in posix mode:
$ bash --posix -c 'y(){ echo z; ... | POSIX print function definition |
1,497,561,233,000 |
I was trying to execute a program which will create a directory on the basis of a complete path provided to it from the prompt and, if the directory already exists it will return an error (for "directory already exists") and ask again for the name in a recursive function.
Here it is what I tried: let us say a file, t... |
The echo always succeeds. Do without it and the subshell:
#!/bin/bash
echo "enter the directory name"
read ab
check(){
if mkdir "$ab" 2>/dev/null; then
echo "directory created "
ls -ld "$ab"
exit
else
echo "try again "
echo "enter new value for directory: "
read ab
che... | Executing a command within `if` statement and on success perform further steps |
1,497,561,233,000 |
This issue is related to Using bash shell function inside AWK
I have this code
#!/bin/bash
function emotion() {
#here is function code end with return value...
echo $1
}
export -f emotion
#I've put all animals in array
animalList=($(awk '{print $1}' animal.csv))
#loop array and grep all t... |
That's probably not the best way to approach the problem.
From awk, all you can do is build a command line that system() passes to sh. So, you need the arguments to be formatted in the sh syntax.
So you'd need:
emotion() {
echo "$i"
}
export -f emotion
awk -v q="'" '
function sh_quote(s) {
gsub(q, q "\\" q q, ... | How can I call a bash function in bash script inside awk? |
1,497,561,233,000 |
Over the years I've collected sort of a library of bash functions the shell and scripts refer to.
To decrease the import boilerplate, I'm exploring options how to reasonably include the library in scripts.
My solution has two parts - first importing configuration (env vars), followed by sourcing the library of functio... |
The problem
Observe:
$ bash -c 'foobar () { :; }; export -f foobar; dash -c env' |grep foobar
$ bash -c 'foobar () { :; }; export -f foobar; bash -c env' |grep foobar
BASH_FUNC_foobar%%=() { :
$ bash -c 'foobar () { :; }; export -f foobar; ksh93 -c env' |grep foobar
BASH_FUNC_foobar%%=() { :
$ bash -c 'foobar () { :... | bash: exported function not visible, but variables are |
1,497,561,233,000 |
Possible Duplicate:
Executing user defined function in a find -exec call
Suppose I have the following bash code:
!#/bin/bash
function print_echo (){
echo "This is print_echo Function" $1;
}
find ./ -iname "*" -exec print_echo {} \;
For each -exec command i get the following error:
find: `print_echo': No such... |
The find does not accept your function as a command because its -exec predicate literally calls C library exec function to start the program. Your function is available only to the bash interpreter itself. Even if you define your function inside your .bashrc file it will be 'visible' only to the bash.
So, if you reall... | Find functions, commands, and builtins [duplicate] |
1,497,561,233,000 |
In my .bash_profile file, I'd like to setup a single command alias that is two commands that execute one after another. The first command takes an argument from the command line and the second is actually script (located in ~/bin with execute permissions).
My profile file has this:
alias pd='function pd2() { pushd "$@... |
aliases do not support input parameters, and there's no need to wrap functions in aliases. Simply use a function:
pd() {
pushd "$@"
set_title_tab
}
pd ~/Documents
| Combine two commands in .bash_profile |
1,497,561,233,000 |
My .bashrc was getting a little long, so I decided to break it up into smaller files according to topic and then call these files from within .bashrc as so
#my long .bashrc file
bash .topic1rc
bash .topic2rc
but, within one of these sub-scripts, I had created a bash function. Unfortunately it is no longer available ... |
If I understand your question correctly, you need to source or . your files. For example, within your .bashrc and taking care of order (only you know):
source .topic1rc
source .topic2rc
source can be shortened to . on the command line for ease of use - it is exactly the same command. The effect of source is to effect... | How to make functions created in a bash script persist like those in .bashrc? |
1,497,561,233,000 |
Forgive me; I'm pretty new to bash files and the like. Here is a copy of my .bashrc:
alias k='kate 2>/dev/null 1>&2 & disown'
function kk {kate 2>/dev/null 1>&2 & disown}
The alias in the first line works fine, but the second line throws:
bash: /home/mozershmozer/.bashrc: line 3: syntax error near unexpected token... |
In bash and other POSIX shells, { and } aren't exactly special symbols so much as they are special words in this context. When creating a compound command like in your function definition, it is important that they remain words, i.e. surrounded by whitespace.
The final command in a single-line function definition lik... | Syntax Error near Unexpected Token in a bash function definition [closed] |
1,497,561,233,000 |
on bash (v4.3.11) terminal type this:
function FUNCtst() { declare -A astr; astr=([a]="1k" [b]="2k" ); declare -p astr; };FUNCtst;declare -p astr
(same thing below, just to be easier to read here)
function FUNCtst() {
declare -A astr;
astr=([a]="1k" [b]="2k" );
declare -p astr;
};
FUNCtst;
declare -p astr
... |
From the man page:
When used in a function, declare makes each name local, as with the local command, unless the -g option is used.
Example:
FUNCtst() {
declare -gA astr
astr=([a]="1k" [b]="2k" )
declare -p astr
}
FUNCtst
declare -p astr
prints
declare -A astr=([a]="1k" [b]="2k" )
declare -A astr=([a]=... | Bash array declared in a function is not available outside the function |
1,497,561,233,000 |
In a bash script I define a function that is called from find. The problem is that the scope of variables does not extend to the function. How do I access variables from the function? Here is an example:
variable="Filename:"
myfunction() {
echo $variable $1
}
export -f myfunction
find . -type f -exec bash -c 'm... |
You could declare variable as an environment variable, i.e.,
export variable="Filename:"
| Scope of variables when calling function from find |
1,497,561,233,000 |
I want to write a init script that should basically run
nvm use v0.11.12 && forever start /srv/index.js
as the user webconfig. nvm is a shell function that is declared in ~webconfig/.nvm/nvm.sh, which is included via source ~/.nvm/nvm.sh in webconfig's .bashrc.
I tried the following:
sudo -H -i -u webconfig nvm
echo... |
The problem here, as is so often the case, is about the different types of shell:
When you open a terminal emulator (gnome-terminal for example), you are executing what is known as an interactive, non-login shell.
When you log into your machine from the command line, or run a command such as su username, or sudo -u ... | Run nvm (bash function) via sudo |
1,497,561,233,000 |
I recently wrote the following bash function:
makeaudiobook () {
count=1
almbumartist=$2
for f in $1; do
preprocess $f > $f-preprocessed
text2wave $f-preprocessed -o $f.wav
lame -b 16 --tt $f --ta $albumartist --tl $albumartist --tn $count $f.wav $f.mp3
rm -rf $f.wav $f-preprocessed
... |
x?? is expanded at the time of function call. So your function is already called with xaa xab xac... .
The simplest way would be to change the ordering of your parameters:
makeaudiobook () {
count=1
almbumartist=$1
shift
for f in "$@"; do
preprocess "$f" > "$f"-preprocessed
text2wave "$f"-preprocessed ... | for loop in bash function |
1,497,561,233,000 |
How do I prefix -p to every argument passed to my function?
Modifying the arguments themselves and creating a new array are both fine.
|
This should work nicely even for complicated arguments with whitespace and worse:
#!/bin/bash
new_args=()
for arg
do
new_args+=( '-p' )
new_args+=( "$arg" )
done
for arg in "${new_args[@]}"
do
echo "$arg"
done
Test:
$ ~/test.sh foo $'bar\n\tbaz bay'
-p
foo
-p
bar
baz bay
| Prefix every argument with -o in BASH |
1,554,126,051,000 |
Is there a way to lookup (just print the completion definition to stdout) currently loaded zsh completion functions.
I understand that they are stored somewhere on my fpath and I could do something like ag $fpath completionname to find the definition in the files.
Is there a cleaner way, a zsh function or something t... |
The name of the completion function for the command foo is $_comps[foo].
To see the code of a function myfunc, run echo -E $functions[myfunc], or just echo $functions[myfunc] if you have the bsd_echo option on, or print -rl $functions[myfunc]. So to see the code of the completion function for the command foo, run echo... | How to look up zsh completion definitions |
1,554,126,051,000 |
Normally when I cat a file like this
it's hard to read without colorizing.
I've managed to get cat to use source-highlight like this:
cdc() {
for fn in "$@"; do
source-highlight --out-format=esc -o STDOUT -i $fn 2>/dev/null || /bin/cat $fn
done; }; alias cat='cdc'
which now produces the following for a recog... |
Define your cdc function as
cdc() {
for fn do
if [[ "${fn##*/}" == .* ]]
then
source-highlight --src-lang=sh --out-format=esc -i "$fn"
else
source-highlight --out-format=esc -i "$fn"
fi 2> /dev/null || /bin/cat "$fn"
done
}
for fn do is ... | How can I make source-highlight colorize .dotfiles by default? |
1,554,126,051,000 |
I like to encapsulate commands within shell-functions using the same name. But to avoid the shell-function calling itself recursively, I specify the complete path of the command as the following example:
less()
{
test 0 -lt $# && echo -ne "\e]2;$@\a\e]1;$@\a" # Window title
/usr/bin/less -i -rS --LONG-PRO... |
Prepend your actual commands (not functions) with command shell builtin, it has exactly the purpose you're looking for. Therefore your shell-function should look that:
mvn()
{
command mvn "$@" 2>&1 |
sed -u '
s/^\[ALL\].*/\o033[1;37m&\o033[0m/
s/^\[FATAL\].*/\o033[1;31m&\o033[0m/
s/^\[ERROR\].*... | Best way to call command within a shell function having the same name [duplicate] |
1,554,126,051,000 |
I have a bash script that contains many common functions definitions for our Linux system.
Is it possible to source it and use functions from another shell flavor (csh and ksh) ?
|
It should be easy enough to create a wrapper script around the functions; for Bash:
#!/bin/bash
doSomething()
{
...
}
doSomethingElse()
{
...
}
FUNCTION_NAME=$1
shift
${FUNCTION_NAME} "$@"
exit $?
Call:
/path/to/functionWrapper.sh doSomething [<param1>] [...]
| Is it possible to use functions declared in a shell flavor in another shell type |
1,554,126,051,000 |
When I create
alias wd='ps -ef | grep java | awk {'print $2 " " $9'} | egrep "(A|B|C|D)"'
or
function wd () {
ps -ef | grep java | awk '{print $2}' ...
}
in my .bashrc file, I get errors. Interestingly, if I source my .bashrc file with the function, it 'compiles', but when executing, gives me:
context is
... |
Why the alias doesn't work
alias wd='ps -ef | grep java | awk {'print $2 " " $9'} | egrep "(A|B|C|D)"'
The alias command receives three arguments. The first is the string wd=ps -ef | grep java | awk {print (the single quotes prevent the characters between them from having a special meaning). The second argument consi... | alias or bash function does not work |
1,554,126,051,000 |
I'm not entirely sure why I'm getting the error in my .bash_profile
syntax error near unexpected token `('
when I use the keyword grom() for my function. I wanted to create a bash function that will just automatically rebase my master branch with origin
# git status
alias gs='git status'
# git stash list
alias gsl='... |
If you're using bash, you may have better luck declaring it as:
function grom() { … }
(Note: function will not work in strict POSIX shells like dash!)
@aug suggested (via edits to this answer) that this is due to a conflicting alias (or, less plausibly, a builtin that somehow got defined).
The reserved word function... | grom() keyword in bash throws unexpected '(' token |
1,554,126,051,000 |
I would like to write a function in bash, then export that function and execute it over ssh. Is that possible, and if yes, how?
I tried
#!/bin/bash
function myfunc() {
echo $1
}
export -f myfunc
but this doesn't seem to work.
|
In the example that you mention in your comment it is parallel that transfers the function to the remote environment (and it works only bash). So you have to use parallel to try it. After defining and exporting (as per Q), you should:
function myfunc() {
echo $1
}
export -f myfunc
parallel --env myfunc -S ... | How to export a function in bash over ssh? |
1,554,126,051,000 |
How can I display a list of shell variables in Bash, not including functions, which often clutter the output, because of the many related to completion?
I have examined declare, and it has an option for limiting the output to functions (declare -f), but not for limiting the output to "plain" shell variables?
|
The command compgen -v will display a list of names of shell variables in the current bash shell session. Also, declare -p, which lists the attributes and values of all variables in a form that is (almost always) suitable for shell input, does not list functions.
| How to display only shell variables (not functions) [duplicate] |
1,554,126,051,000 |
How do I use the positional parameters (which are given from the command line) inside of a function declaration?
When inside the function definition, $1 and $2 are the only the positional parameters of the function itself, not the global positional parameters!
|
It's not exactly clear to me what you are asking, but the following example might clear things up:
$ cat script
#!/usr/bin/env bash
echo "Global 1st: ${1}"
echo "Global 2nd: ${2}"
f(){
echo "In f() 1st: ${1}"
echo "In f() 2nd: ${2}"
}
f "${1}" "${2}"
$ ./script foo bar
Global 1st: foo
Global 2nd: bar
In f(... | Use of positional parameters inside function defintion |
1,554,126,051,000 |
How does Bash initialize local variables? Will the following commands always do the same thing (when used inside a function)?
local foo
local foo=
local foo=""
|
local foo="" and local foo= are exactly equivalent. In both cases, the right-hand side of the equal sign is an empty string.
local foo and local foo= are different: local foo leaves foo unset while local foo= sets foo to an empty string. More precisely, local foo creates a local variable, and that variable is initiall... | Bash local variable initialization |
1,554,126,051,000 |
Is there a way to return a specific value in an echoing function?
return allows me to return an exit status for the function. I need to return a more sophisticated data structure such as an array, or a string. Usually I would need to echo the value I want to be returned. But what if I need to echo informative messages... |
You could output all the other content directly to screen assuming you don't ever want to do anything with it other than display.
Something similar to this could be done
#!/bin/bash
function get_usr_choices() {
#put everything you only want sending to screen in this block
{
echo these
... | Get specific result from function |
1,554,126,051,000 |
This is probably a very easy to answer question, but I could not find any questions already asking this due to different wording when writing titles.
Running help alias on my bash prompt returns only this:
alias: alias [-p] [name[=value] ... ]
Then a very short text that has nothing to do with what I'm asking.
I als... |
You need to use function, not alias, so that
mancat () { man "$1" | cat ; }
mancat grep
will do what you want.
Similarly
mygrep () { "$1" "$3" "$2" | "$1" -v "$4" | "$5" -n1; }
mygrep grep pattern1 file pattern2 head
mygrep grep pattern1 file pattern2 tail
will grep for pattern1 in the file and then select only line... | How do I define alias with variables which can be changed at runtime? |
1,554,126,051,000 |
I have this function to get MAC address from IP:
ip2arp() {
local ip="$1"
ping -c1 -w1 "$ip" >/dev/null
arp -n "$ip" | awk '$1==ip {print $3}' ip="$ip"
}
What is the right way for using it later? Save to /usr/bin as sh and make it executable, or save it in a home directory and make an alias in bash? Is t... |
If it's only for your personal use then you could add it to your shell's initialization file as a function, e.g. ~/.bashrc.
For a summary of the different initialization files in Bash you can consult the Bash Guide for Beginners:
Bash Guide for Beginners - Section 3.1: Shell Initialization Files
Also see the Bash Re... | How to save a function in bash for later use? |
1,554,126,051,000 |
I need two ways to terminate a part of my bash script.
Either a counter reaches a predefined number, or the user manually forces the script to continue with whatever the value the counter currently has.
Specifically - I'm listing USB drives. If there is 15 of them, the function that counts them exits and the script ca... |
Let me start by saying, you could just inline all the stuff you have in scannew, since you're waiting anyway, unless you intend to scan again at some other point in your script. It's really the call to wc that you're concerned might take too long, which, if it does, you can just terminate it. This is a simple way to s... | Wait for a process to finish OR for the user to press a key |
1,554,126,051,000 |
I have lots of functions in my bashrc, but for newly created ones I often forget the name of the function.
So for example, when I have defined this function in my .bashrc:
function gitignore-unstaged
{
### Description:
# creates a gitignore file with every file currently not staged/commited.
# (except the ... |
Note that with zsh, you can do:
printf '%s() {\n%s\n}\n\n' ${(kv)functions[(R)*gitignore*]}
To retrieve the information from the currently defined functions (that doesn't include the comments obviously).
Now, if you want to extract the information from the source file, then you can't do reliably unless you implement... | How can I print out the complete function declaration of any function which has a specific string inside it? |
1,554,126,051,000 |
i did not yet found a solution to this. Anyone a hint?
i sometimes write bash functions in my shell scripts and i love to have my scripts being verbose, not just for debugging. so sometimes i would like to display the "name" of a called bash function as a "variable" in my scripts.
what i did sometimes is setting just... |
Sometimes it's enough to read man bash:
FUNCNAME
An array variable containing the names of all shell
functions currently in the execution call stack. The
element with index 0 is the name of any
currently-executing shell function. The bottom-most
elemen... | how to get or reflect the name of the bash function which is called? [duplicate] |
1,554,126,051,000 |
I'm performing several commands on large files from within a bash script. In order to monitor the progress I use the pv command.
An example command could look like this
cat $IN_FILE | pv -w 20 -s $(du -sb $IN_FILE | awk '{print $1}') | grep ...
The script contains multiple commands of similar structure, rather than h... |
In your function definition, I would suggest replacing:
echo "cat $1 | pv -w 20 -s ${__size}"
with just:
cat $1 | pv -w 20 -s ${__size}
This way, the function itself will execute this bit of code, without requiring a call to eval in the caller.
| How to use a bash function like a regular command in a pipe chain? |
1,554,126,051,000 |
I want to be able to name a terminal tab so I can keep track of which one is which. I found this function (here) and put it in my .bashrc:
function set-title() {
if [[ -z "$ORIG" ]]; then
ORIG=$PS1
fi
TITLE="\[\e]2;$*\a\]"
PS1=${ORIG}${TITLE}
}
and now when I call set-title my new tab name the tab name is... |
Instant of using function set-title you can create command with this functionality, so remove function set-title() that you add from ~/.bashrc and create a file /usr/local/bin/set-title:
#!/bin/bash
echo -ne "\033]0;$1\007"
Add chmod: chmod +x /usr/local/bin/set-title.
And after you re-open terminal you can use this ... | Call a .bashrc function from a bash shell script |
1,554,126,051,000 |
I have written a function which acts in a similar way to tee but also pre-pends a datestamp. everything works fine except when i want to output to a file which is only root writable (in my case a logfile within /var/log). I've simplified the following code snippet to just include the bits which are not working:
#!/bin... |
it's generally bad practice to put sudo in a script. A better choice would be to call the script with sudo from ~/.bash_logout or wherever else you want to use it, if you must, or better still just make /var/log/test.log world-writable.
| How can I use sudo within a function? |
1,554,126,051,000 |
On small systems where there is no locate installed, How would an alias look like that gets the same result as locate?
I can imagine find can produce the same output so an alias could look like
alias locate="find / -name"
But that doesn't seem to work the same as locate:
locate test
will only find files with the na... |
To improve the huge speed impact on find you could simulate something like locate
alias locate="if [ ! -e /tmp/locate.db -a ! -e /tmp/locate.lockdb ]
then touch /tmp/locate.lockdb
trap \"rm /tmp/locate.lockdb; rm /tmp/locate.db; exit\" SIGHUP SIGINT SIGTERM
find /|tee /tmp/locate.db
chmod 666 /tmp/locate.db
rm /tmp/lo... | locate alias with find |
1,554,126,051,000 |
Taking how reference the following code for simplicity
#!/bin/bash
number=7
function doSomething() {
number=8
}
doSomething
echo "$number"
It prints 8.
But with:
#!/bin/bash
number=7
function doSomething() {
number=8
}
$(doSomething)
echo "$number"
It prints 7.
I have the following questions:
What are th... |
You are experiencing the subtleties of the Command Substitution.
The call
doSomething
is a simple function call. It executes the function, pretty much as if you had copy-and-pasted the commands of the function to the place where you call it. Hence, it overwrites the variable number with the new value 8.
The call
$(do... | Script function call: function vs $(function) |
1,554,126,051,000 |
I am presently writing a Bash function to convert all the man pages listed by equery files <PACKAGE> | grep /usr/share/man/man (if you are unfamiliar equery is a tool used on Gentoo-based systems that is from the app-portage/gentoolkit package) into HTML files and one bit of information I need in order to do this is ... |
Using parameter expansion:
line="/usr/share/man/man5/xpak.5.bz2"
# printf "%s\n" "${line##*/}"
# xpak.5.bz2
file="${line##*/}"
printf "%s\n" "${file%.*}"
xpak.5
In Zsh, you can do nested parameter expansions:
printf "%s\n" "${${line##*/}%.*}"
xpak.5
| How do I remove all but the file name (with no extension) from a full file path? [duplicate] |
1,554,126,051,000 |
I'm writing a function that will make a REST API calls which could be either GET, PUT, DELETE, POST, etc.
I would like to feed this method to the function as a parameter and add it to the options array for that single function call. Is this possible?
Currently I am solving this by creating a separate local array bu... |
One option would be to explicitly use a subshell for the function, then override its local copy of the array, knowing that once the subshell exits, the original variable is unchanged:
# a subshell in () instead of the common {}, in order to munge a local copy of "options"
some_func () (
local urn=$1
shift
... | Add to array only within scope of function |
1,554,126,051,000 |
I want to define a function, and call that function every n seconds. As an example:
function h
echo hello
end
Calling h works:
david@f5 ~> h
hello
But when using watch, it doesn't...
watch -n 60 "h"
...and I get:
Every 60.0s: h f5: Wed Oct 10 21:04:15 2018
sh: 1: h: not fou... |
Another way would be to save the function, then ask watch to invoke fish:
bash$ fish
fish$ function h
echo hello
end
fish$ funcsave h
fish-or-bash$ watch -n 60 "fish -c h"
funcsave saves the named function definition into a file in the path ~/.config/fish/functions/, so ~/.config/fish/function/h.fish in the above... | Define function in fish, use it with watch |
1,554,126,051,000 |
I have a function defined in my .bashrc that I would like to bypass:
function func() {
// func
}
export -f func
When I run env -i func I can access the func command without the function in the way, but if I try "func" or \func then I don't have any luck.
I read on another post that \ should work to bypass bash fun... |
The official way to prevent function definitions from being used by the shell is to call:
command func
See: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/command.html
| Does \ work for escaping functions? |
1,554,126,051,000 |
I have this code that does work:
get_parameter ()
{
echo "$query" | sed -n 's/^.*name=\([^&]*\).*$/\1/p' | sed "s/%20/ /g"
}
But I want to replace the "name" with the parameter that I pass to get_parameter
get_parameter ()
{
echo "$query" | sed -n 's/^.*$1=\([^&]*\).*$/\1/p' | sed "s/%20/ /g"
}
NAME=$( get_para... |
Quoting: In short, variables are not replaced with their values inside 'single-quoted' strings (aka. "variable substitution"). You need to use any one of "double quotes", $'dollar quotes', or
<<EOF
here strings
EOF
| How to pass a string parameter on bash function? |
1,554,126,051,000 |
I was trying to create a function that loops over inputs and executes a command - regardless of how they are delimited.
function loop {
# Args
# 1: Command
# 2: Inputs
for input in "$2" ; do
$1 $input
done
}
declare -a arr=("1" "2" "3")
$ loop echo "$arr[@]"
1... |
You have not called the array properly. $arr will only expand to the first element in the array and $arr[@] will expand to the first element with the literal string [@] appended to it.
To call all elements of an array use: "${arr[@]}"
The other issue you have is that $2 only contains the second positional parameter, ... | Generic function to loop over inputs and execute a command in bash? |
1,554,126,051,000 |
Are there any relevant standards that dictate what an implementation of sh must do with an empty function?
The following snippet defines a function with zero statements
a() {
}
The subshell version appears to be treated identically
a() (
)
ash and zsh accept either construction as a function that does nothing and ha... |
No, a function may not have an empty body between braces in a conforming application.
POSIX defines a function definition command as:
fname ( ) compound-command [io-redirect ...]
where all those words are placeholders for things defined elsewhere in the specification. compound-command is the body of the function.
A ... | Can a function in sh have zero statements? |
1,554,126,051,000 |
*nix commands (and functions?) have a number with them, like fsck(8), killall(1), etc.
What does the number mean?
|
The character explicitly specifies the section that the manual page is part of. On most Unices, the section definitions are as follows:
General/user commands
System calls
Library functions
Special files and drivers
File formats
Games and screensavers
Miscellanea and conventions
System administration commands, privele... | What does the "(8)" in fsck(8) mean? [duplicate] |
1,554,126,051,000 |
I try to understand the seek(2) function from Unix version 6.
This example:
seek(0,0,2)
So the first argument is the file descriptor. And 0 would be the standard input.
The second argument is the offset, which is 0.
And the third argument tells us according to man page "the pointer is set to the size of the file plus... |
The seek(0, 0, 2) will skip over all data that is buffered up for file descriptor 0. So after this command, the next read from that filedescriptor will not read anything that was buffered.
I think if you examine the code and understand what the actual purpose is, you'll understand that even though file descriptor 0 i... | seek function in unix |
1,554,126,051,000 |
I'm trying to set the fish history pager to be bat -l fish for syntax highlighting.
(i.e. set the PAGER environment variable bat -l fish just for the history command).
I tried:
# 1:
alias history "PAGER='bat -l fish' history"
# results in "The function “history” calls itself immediately, which would result in an infi... |
Two things are happening here:
fish's alias actually creates a function.
fish ships with a default history function already.
So when you write
alias history "PAGER='bat -l fish' history"
what you actually have is the recursive function
function history
PAGER='bat -l fish' history $argv
end
Some solutions:
us... | how to alias the `history` function in fish shell |
1,554,126,051,000 |
#!/bin/sh
execute_cmd()
{
$($@)
}
execute_cmd export MY_VAR=my_val
echo ${MY_VAR}
Since $() executes in a sub-shell, $MY_VAR isn't set properly in the shell the script is running.
My question, how can I pass the export command to a function and execute it in the current shell the script is running in?
|
You should check Gilles' answer for all the details. In short, you can use eval instead of $():
execute_cmd()
{
eval "$@"
}
From bash manual:
eval [arguments]
The arguments are concatenated together into a single command, which is then read and executed, and its exit status returned as the exit status of eval. ... | passing export command to function in shell script |
1,554,126,051,000 |
A typical way for a shell function to "return" its result is to assign it to some global variable.
Is there any convention/best-practice on the name of this variable?
|
REPLY is commonly used for that. It's used by read and select in bash, ksh and zsh at least.
In the zsh documentation:
REPLY
This parameter is reserved by convention to pass string values
between shell scripts and shell builtins in situations where a
function call or redirection are impossible or... | Are there any conventions for the name of global variable that holds function's result? |
1,554,126,051,000 |
I have created lots of directories and I would to make my life lazy and to auto cd into the directory that I made with the option of -g with the result of mkdir -g foo
The terminal would be like this:
User:/$ mkdir -g foo
User:/foo/$
I have looked at this page but with no success.
Is there a one-liner that allows me... |
Use the command builtin to call an external command, bypassing any function of the same name. Also:
What follows if is an ordinary command. To perform a string comparison, invoke the test built-in, or the [ builtin with the same syntax plus a final ], or the [[ … ]] construct which has a more relaxed syntax. See usin... | how to add a custom option to the mkdir command |
1,554,126,051,000 |
If in zsh, I type set and see precmd_functions=(_precmd_function_dostuff _precmd_function_domore).
Where are _precmd_function_dostuff and _precmd_function_domore defined (i.e. are they defined in a file? which file?)?
I can type functions to see the definitions of _precmd_function_dostuff and _precmd_function_domore, ... |
In zsh 5.3 or above,
type _precmd_function_domore
should return something like
_precmd_function_domore is a shell function from /usr/local/etc/zshrc.d/80-PetaLinux
With zsh 5.4 or above, you can also use:
echo $functions_source[_precmd_function_domore]
When you run zsh with the xtrace option (like with zsh -x), it ... | In zsh, where are precmd_functions defined? |
1,554,126,051,000 |
The following works great on the command-line:
$ ffmpeg -i input.m4a -metadata 'title=Spaces and $pecial char'\''s' output.m4a
How do I parameterize this command and use it in a script/function? I would like to add multiple metadata tags like this:
$ set-tags.sh -metadata 'tag1=a b c' -metadata 'tag2=1 2 3'
update:
... |
"$@" does exactly what you want provided that you use it consistently. Here's a little experiment for you:
script1.sh:
#! /bin/sh
./script2.sh "$@"
script2.sh:
#! /bin/sh
./script3.sh "$@"
script3.sh:
#! /bin/sh
printf '|%s|\n' "$@"
With this the arguments stay unmolested all the way down:
$ ./script1.sh -i inpu... | Passing arguments with spaces and quotes to a script (without quoting everything) |
1,554,126,051,000 |
I know I can write bash scripts like:
foo() {
echo $1;
}
but can I define a function that writes:
foo(string) {
echo $string;
}
I just can't find my way out of this.
|
The only available form is the first one; see the manual for details.
To use named parameters, the traditional technique is to assign them at the start of your function:
foo() {
string=$1
# ...
echo "${string}"
}
| Bash function with arguments |
1,554,126,051,000 |
I am having trouble with what should be a simple bash script.
I have a bash script that works perfectly:
function convert_to ()
x_max=2038
y_max=1146
x_marg=100
y_marg=30
x_grid=150
y_grid=150
if (("$x_pos" > "($x_marg+($x_grid/2))")); then
x_pos=$((x_pos-x_marg))
x_mod=$((x_pos%x_grid))
x_pos=$((x_pos/x... |
In bash, the argument separators are spaces, so :
instead of :
x_pos="$(convert_coordinates $x_pos, $x_marg, $x_grid, $x_max)"
do
x_pos="$(convert_coordinates $x_pos $x_marg $x_grid $x_max)"
| functions arguments |
1,554,126,051,000 |
How can I use the integer value returned by a function in shell script that takes some arguments as input?
I am using the following code:
fun()
{
echo "hello ${1}"
return 1
}
a= fun 2
echo $a
I am not sure how should I call this function. I tried the methods below, bot none of them seems to work:
a= fun 2
a=... |
The exit code is contained in $?:
fun 2
a=$?
| How to call a shell function |
1,347,105,879,000 |
I just discovered this useful bit of code on this useful-looking website.
#!/bin/sh
exec tclsh "$0" ${1+"$@"}
proc main {} {
set lines [lrange [split [read stdin] \n] 0 end-1]
set count [llength $lines]
for {set idx_1 0} {$idx_1 < $count} {incr idx_1} {
set idx_2 [expr {int($count * rand())... |
Tell tclsh to read the script from a different file descriptor, and use a here document to pass the script.
shuffle () {
tclsh /dev/fd/3 "$@" 3<<'EOF'
proc main {} {
…
}
main
EOF
}
| Is there any way I can fit this into my ~/.bashrc as a function? |
1,347,105,879,000 |
I have the following bash function:
lscf() {
while getopts f:d: opt ; do
case $opt in
f) file="$OPTARG" ;;
d) days="$OPTARG" ;;
esac
done
echo file is $file
echo days is $days
}
Running this with arguments does not output any values. Only after running the function without arguments, and ... |
Though I can't reproduce the initial run of the function that you have in your question, you should reset OPTIND to 1 in your function to be able to process the function's command line in repeated invocations of it.
From the bash manual:
OPTIND is initialized to
1 each time the shell or a shell script... | bash function arguments strange behaviour |
1,347,105,879,000 |
Doing some code refactoring, and I realized I don't know if this matters at all:
The function definition is going to be sourced from another file (a sort of library). The function uses certain variables within the function body. Those variables will be set by the time the function is actually called in the script, b... |
fn(){ printf %s\\n "${v-not set}"; }
v=value; fn; unset v; fn
value
not set
A shell function is a literal string stored in the shell's memory. At define time it is parsed, but is not evaluated for expansions (other than shell aliases) or redirections. These are only evaluated at call time.
In fact, and somewhat rel... | Is there any danger to using an unset variable in a bash function definition? |
1,347,105,879,000 |
I want to define the function cpfromserver in bash so that when I run
$ cpfromserver xxx yyy zzz
the result is the same as if I had typed
$ scp [email protected]:"/some/location/xxx/xxx.txt /some/location/xxx/xxx.pdf /some/location/yyy/yyy.txt /some/location/yyy/yyy.pdf /some/location/zzz/zzz.txt /some/location/zzz/z... |
Try this way:
cpfromserver () {
files=''
for x in "$@"
do
files="$files /some/location/$x/$x.txt /some/location/$x/$x.pdf"
done
scp [email protected]:"$files" /somewhere/else/
}
Important caveat from comments: "It's worth noting for posterity that this solution definitely won't work for co... | Write bash function which operates on list of filenames |
1,347,105,879,000 |
I'm using function like this.
$ find-grep () { find . -type f -name "$1" -print0 | xargs -0 grep "$2" ; }
After I type:
$ find-grep *.c foo
I want to get expanded last command string. In this case:
find . -type f -name "*.c" -print0 | xargs -0 grep "foo"
Is there way to do it easily?
|
A saner version of @slm's:
find-grep() {
cmd=(find . -type f -name "$1" -exec grep "$2" {})
printf '%q ' "${cmd[@]}"
printf '+\n'
"${cmd[@]}" +
}
(no need for pipes or xargs here) Or:
find-grep () (
set -x
find . -type f -name "$1" -exec grep "$2" {} +
)
(note the () instead of {} to start a subshell to ... | How to show last command with expanding function in bash |
1,347,105,879,000 |
I want to write a convenience function which loads all the matlab scripts it's passed on the command line. The syntax would look like
fmatlab myscript1.m myscript2.m ... mystriptN.m
I can easily do some preset number of scripts. For instance, if I give it just a single script:
function fmatlab () {
$MYMATLA... |
Looks like you want:
fmatlab () {
$MYMATLABPATH/matlab -r "edit $*" &
}
When $* is used inside double quotes, it joins all the parameters using a space (by default).
| Writing a bash function to autoload matlab scripts |
1,347,105,879,000 |
> cat b.txt
function first
{
sleep 1
echo $(echo $$)
}
function second
{
openssl enc -aes-256-cbc -k "$(first)"
}
echo nyi | second | second | second
>
> time sh -x b.txt
+ echo nyi
+ second
+ second
+ second
++ first
++ sleep 1
++ first
++ sleep 1
++ first
++ sleep 1
+++ echo 32383
++... |
The parts of a pipeline are started (close to) simultaneously.
All three invocations of second will start at the same time. The three subshells that this gives rise to will invoke first to expand "$(first)" and the three sleep 1 calls will happen concurrently (you can see in the trace output that they do happen).
It's... | Function in function will not be called multiple times if requested? |
1,347,105,879,000 |
What is the dash equivalent to bash's:
compgen -A function
which lists the names of the declared functions.
|
As far as I can tell there is no equivalent. dash has a very small number of built-in commands and none of them list the declared functions.
| dash: List declared functions |
1,347,105,879,000 |
Somehow I'm not able to execute the following mapping:
function! s:MySurroundingFunctionIWantToKeep()
let s:Foobar={'foo': 'bar'}
map \42 :echo <sid>Foobar.foo<cr>
endfunction
call s:MySurroundingFunctionIWantToKeep()
I thought it works the same way as it does with a script-local function:
function! s:MySurroundi... |
There is no way (that I know of) to directly access script-local variables outside the context of that script; <SID> only works for functions (and only in mappings).
You could provide indirect access through a function, though:
function! s:FoobarHash()
return s:Foobar
endfunction
function! s:MySurroundingFunctionIWa... | How to reference a script-local dictionary in a Vim mapping? |
1,347,105,879,000 |
I wrote a ksh function for git checkout (I've removed some irrelevant proprietary components for the sake of the public question, if you're wondering why it's useful to me):
# Checkout quicker
checkout(){
if [ "$1" == "master" ]; then
git checkout master
else
git checkout $1
fi
}
When I look at the function on ... |
Looks like you may have hit the bug later fixed by this commit. I can reproduce it with CentOS 7's ksh93 with:
$ cat a
# Checkout quicker
checkout(){
if [ "$1" == "master" ]; then
git checkout master
else
git checkout $1
fi
}
$ . ./a
$ functions checkout
checkout(){
if [ "$1" == "master" ]; then
git checkout ... | How does my function break `functions`? |
1,347,105,879,000 |
Normally I like to have all of the debug output of a script go to a file, so I will have something like:
exec 2> somefile
set -xv
This work very will in bash, but I have noticed in ksh it behaves differently when it comes to functions. I noticed when I do this in ksh, the output does not show the function trace, onl... |
From the documentation:
Functions defined by the function name syntax and called by name execute in the same process as the caller and
share all files and present working directory with the caller. Traps caught by the caller are reset to their
default action inside the function.
Whereas
Funct... | set -xv behavior in ksh vs bash |
1,347,105,879,000 |
Context:
I have an old bash script with a big section parsing its arguments. It happens now that I need to call this section twice, so I plan to move it to a function to avoid code duplication.
The problem:
In that section, set --, shift and $@ are used, meaning that they won't apply to the script anymore, but to t... |
Disclaimer:
From the discussion above, I implemented a solution. This is not, by far, the one I dreamed of, because of the verbosity of ${args_array[1]}, compared to $1. Makes the source less readable. So improvements, or a better solution are still welcome.
Source:
Tested, something like this:
#!/bin/bash
########... | Get and set the script arguments from within a function in bash |
1,347,105,879,000 |
I would like to ask about passing parameters into functions.
I tried this:
function_name $var1 $var2
but usually (sometimes it printed error) it didn't make any difference whether I passed them or not. I mean it perfectly worked when I called it only with function_name. So my question is: Is it necessary to give th... |
Bash doesn't check number of arguments passed to a function because there are no prototypes as in C. From https://www.gnu.org/software/bash/manual/bash.html#Shell-Functions:
Shell functions are a way to group commands for later execution using
a single name for the group. They are executed just like a "regular"
c... | What happens if I pass too few parameters to a shell function? |
1,347,105,879,000 |
I know that in shell-scripting an "exit" usually means voluntarily or at least successfully terminating a session (or a process within a session) and that there are several different exit modes; the following are these I know:
1. A simple exit command
If I'm in the first shell-session (shell-session 0) it will usually... |
an "exit" usually means voluntarily or at least successfully terminating
At least the POSIX text seems to use exit solely for voluntary termination of a process, as opposed to being killed for an outside reason. (See e.g. wait()) A process being killed by a signal hardly counts as a success, so any successful termin... | What exit modes exist in shell-scripting in general and in Bash in particular? |
1,347,105,879,000 |
I need to run these commands very often:
sudo apt-get install <package>
sudo apt-get remove <package>
Can I make it simple like:
install <package>
remove <package>
I think I need to write a function like this:
function install(){
sudo apt-get install <package>
}
...and then need to copy paste to some location i do... |
Use shell aliases, they won't interfere with other scripts/commands, they are only replaced when the command has been typed interactively:
alias install="sudo apt-get install"
You may place this in your shell configuration file (~/.bashrc for example) and it will be defined in all your shell sessions.
| creating simple command for sudo apt-get install? |
1,347,105,879,000 |
I know that I can use unset -f $FUNCTION_NAME to unset a single function in bash / zsh, but how do I unset all functions?
|
In the zsh shell, you may disable all functions using
disable -f -m '*'
(literally, "disable each function whose name matches *").
You may then enable them again with the analogous enable call.
You may also use unset in a similar way to remove the functions completely from the current environment:
unset -f -m '*'
| How do I unset all functions in zsh? |
1,347,105,879,000 |
There are a couple of questions related to the fork bomb for bash :(){ :|: & };: , but when I checked the answers I still could not figure out what the exactly the part of the bomb is doing when the one function pipes into the next, basically this part: :|: .
I understand so far, that the pipe symbol connects two com... |
Short answer: nothing.
If a process takes in nothing on STDIN, you can still pipe to it. Simiarly, you can still pipe from a process that produces nothing on STDOUT. Effectively, you're simply piping a single EOF indicator in to the second process, that is simply ignored. The construction using the pipe is simply a va... | What exactly is the function piping into the other function in this fork bomb :(){ :|: & };:? |
1,347,105,879,000 |
I just wrote a function in my ~/.bashrc that will let me create a folder for a new website with one command. The function looks like this:
function newsite() {
mkcd "$*" # mkdir and cd into it
mkdir "js"
mkdir "imgs"
touch "index.html"
touch "main.css"
vim "index.html"
}
Now what I would like to do is, i... |
jw013's idea and HaiVu's answer are both correct. However for the sake of completeness for anyone who comes upon this question wanting the answer, here it is;
function newsite() {
mkcd "$*" # mkdir and cd into it
mkdir "js"
mkdir "imgs"
cat > index.html <<'EOI'
<html>
<head>
</head>
<body>
</body>
</html>
EOI... | Script to create files in a template |
1,347,105,879,000 |
I would like to create a bash function that, given a string, it count the depth level of nested parentheses, and return -1 if the parentheses are not balanced:
function countNested(){
str="$1"
n_left=$(echo $str | grep -o '(' | grep -c '(' )
n_right=$(echo $str | grep -o ')' | grep -c ')' )
# if the n_left... |
You could do the check character-by-character, that'd let you detect cases where there is a right parenthesis without the corresponding left one. You could do it Bash, but if you care about performance, some other tool is probably better. E.g. with awk:
$ cat parens.awk
#!/usr/bin/awk -f
{
n = 0;
max = 0;
... | Bash function to count the number of nested parentheses |
1,347,105,879,000 |
I'm trying to call a self-defined function funk_a in strace but it doesn't seem to find it.
I confirmed that funk_a can be called by itself.
I appreciate any opinions.
$ source ./strace_sample.sh
$ funk_a
Earth, Wind, Fire and Water
$ funk_b
Get on up
strace: Can't stat 'funk_a': No such file or directory
$ dpkg -p... |
strace can only strace executable files.
funk_a is a function, a programming construct of the shell, not something you can execute.
The only thing strace could strace would be a new shell that evalutes the body of that function like:
strace -o trace_output.txt -Ttt bash -c "$(typeset -f funk_a); funk_a"
(I removed -c... | strace not finding shell function with "Can't stat" error |
1,347,105,879,000 |
function mv1 { mv -n "$1" "targetdir" -v |wc -l ;}
mv1 *.png
It does only move the first .png file it finds, not all of them.
How can I make the command apply to all files that match the wildcards?
|
mv1 *.png first expands the wildcard pattern *.png into the list of matching file names, then passes that list of file names to the function.
Then, inside the function $1 means: take the first argument to the function, split it where it contains whitespace, and replace any of the whitespace-separated parts that contai... | Why does a file move/copy function only move one file at a time when using the “*” wildcard? |
1,347,105,879,000 |
So I tried making a function in a script that creates a new variable for each argument when running the script. This is my code:
#!/bin/bash
# Creating function log
#ARG1=${1}
log() {
echo "You called DA LOG FUNCTION!!!1!!11one111!"
}
log
#echo "${1}"
#echo "$ARG1"
fcta() {
for ((x=0;x<1000;++x)); do
"a$x"... |
In your function there is a do but no matching done to close the command list.
Try shellcheck to verify your scripts. This is a report of detected bugs and suspicious points in your script:
Line 16:
for ((x=0;x<1000;++x)); do
^-- SC1009: The mentioned syntax error was in this for loop.
^-- SC1073: Couldn't p... | Syntax error while calling a function |
1,347,105,879,000 |
I have a basic script to find the max of 2 numbers using a user-defined function; but, I need to convert it to accept 4 numbers, and I am having a hard time. Here is the script.
#!/bin/bash
echo $1 $2 | awk '
{
print max($1, $2)
}
function max(a, b) {
return a > b ? a: b
}'
You would simply execute it by do... |
You can use the 2-argument function - multiple times:
$ cat scriptname
#!/bin/bash
echo $1 $2 $3 $4 | awk '
function min(a, b) {
return a < b ? a: b
}
{
print min(min(min($1,$2),$3),$4)
}'
then for example
$ ./scriptname 3 1.2 -0.4 77
-0.4
If you're required to write it as a 4-argument function, then I'd... | User-defined function for finding max of 4 numbers |
1,347,105,879,000 |
Since it overwrites my history when used in multiple terminals, I want to turn off the functionality fc -W. Unfortunately I have a habit of typing it often.
I think it's not possible to make an alias, since there is a whitespace in fc -W.
So I tried making a function, something like this:
# Make sure to never invoke f... |
Use builtin:
builtin fc "$@"
This will ensure that the built-in fc command is called.
Style: The diagnostic message should go to the standard error stream and the function should return a non-zero status when failing:
echo 'Sorry, can not do that' >&2
return 1
| Turn off one flag of command and infinite recursion |
1,347,105,879,000 |
This would probably never be the BEST approach to something, but I'm wondering if it's even possible.
Something like:
awk '/function_i_want_to_call/,/^$/{print}' script_containing_function | xargs source
function_i_want_to_call arg1 arg2 arg3
Except actually working.
|
First you need to rigorously determine what command will produce the specific part you want to source. For a trivial example, given the file
var1=value1
var2=value2
you could set only var1 using head -n1 filename. This could be a pipeline of arbitrary complexity, if you wanted.
Then run:
source <( pipeline_of_arbitra... | Source only part of a script from another script? |
1,347,105,879,000 |
IMPORTANT: do not use eval! (I learned this later..)
In a function, eval expands sleep to its alias, so I prevent the endless loop this way:
function FUNCexecEcho() {
echo "EXEC: $@";
shopt -u expand_aliases
eval "$@";
shopt -s expand_aliases
};
alias sleep='FUNCexecEcho sleep ';
sleep 10
But then, all other... |
Using eval is wrong in the first place. The shell has already evaluated what you pass to FUNCexecEcho, evaluating a second time is wrong and potentially dangerous. In your code, you're also discarding the exit status of the command.
FUNCexecEcho() {
echo "EXEC: $@"
"$@"
}
(no problem with aliases there unless yo... | how to prevent alias expansion by `eval` to an arbitrary alias, and keep the endless loop protection on a function? |
1,347,105,879,000 |
I want to construct a function that will change its user input prompt based on its parameter.
my_fucntion takes 1 parameter as db_host after prompting the user for input:
function provide_host () {
echo "Enter NAME OR IP OF ${function_param1} DATBASE HOST: "
read global function_param1_db_host
}
So if I call ... |
You can use $1 to get the first parameter:
function provide_host () {
echo "Enter NAME OR IP OF $1 DATBASE HOST: "
read global function_param1_db_host
}
or to convert it to upper case:
function provide_host () {
echo "Enter NAME OR IP OF ${1^^} DATBASE HOST: "
read global function_param1_db_host
}
Th... | BASH: is it possible to change a prompt of function based on its parameter? |
1,347,105,879,000 |
I have a findn function:
findn () {
find . -iname "*$1*"
}
Using this function has one downside that I cannot use -print0 | xargs -0 command (I am using mac) following findn filename to extend the functionality of the find command if the filename contains empty spaces.
So, is there anyway I can keep both the func... |
One way with GNU find or compatible (-iname is already a GNU extension anyway) could be to define the function as:
findn() (
if [ -t 1 ]; then # if the output goes to a terminal
action=-print # simple print for the user to see
else
action=-print0 # NUL-delimited records so the output can be post-processed... | find - how do i make an alias to do something like (find . -iname '*$1*')? |
1,347,105,879,000 |
I am using the following script, so as to call a function that is supposed to iterate over an array.
#!/bin/bash
function iterarr {
for item in "$1"
do
echo "$item"
done
}
myarr=(/dir1/file1.md /dir1/file2.md README.md)
iterarr "${myarr[@]}"
However, when I execute it, it gives the following ou... |
iterarr "${myarr[@]}" will expand to iterarr '/dir1/file1.md' '/dir1/file2.md' 'README.md' and in your loop you only reference the first argument with "$1". Instead use "$@" to loop over all of the arguments.
#!/bin/bash
function iterarr {
for item in "$@"
do
echo "$item"
done
}
myarr=(/dir1/file... | Function to iterate over array |
1,347,105,879,000 |
My bash script sources a script file (call it file2.sh) according to an argument. (It is either sourced or not.) The script file2.sh contains a function "foo" (call it a modified or improved version of foo).
The script also sources another file (file1.sh) which contains the original function "foo". This one (file1.sh)... |
You can flag your function as 'read only' in file2.sh.
Note: this will cause warnings when file1.sh later tries to define (redefine) the function.
Those warnings will appear on stderr and could cause trouble. I don't know if they can be disabled.
Further note: this MIGHT cause the scripts to fail, if they are checkin... | Bash source -- select the right function when two sourced files have the same function name? |
1,347,105,879,000 |
I try to put find inside function and catch an argument passed to this function with the following minimal work example:
function DO
{
ls $(find . -type f -name "$@" -exec grep -IHl "TODO" {} \;)
}
But, when I execute DO *.tex, I get “find: paths must precede expression:”. But when I do directly:
ls $(find . -t... |
There are a few issues in your code:
The *.tex pattern will be expanded when calling the function DO, if it matches any filenames in the current directory. You will have to quote the pattern as either '*.tex', "*.tex" or \*.tex when calling the function.
The ls is not needed. You already have both find and grep tha... | find inside shell function |
1,347,105,879,000 |
In an attempt to go around an annoying aspect of tmux, I have the following code in my .bashrc file:
alias emcs="command emacs"
# Fix emacs in tmux
emacs () {
if [ $TERM != "xterm" ]
then
TERM=xterm emacs "$@"
else
emacs "$@"
fi
return;
}
The alias is simply for easier access to t... |
Take a look at your function. In this example, I have changed some names to indict the guilty, and struck some irrelevancies to your problem:
recurse{} (
recurse "$@"
}
What do you think this will do when invoked?
To fix this, you can call out the explicit binary:
emacs () {
if [ $TERM != "xterm" ]
then
... | How do I make a working emacs alias function? |
1,347,105,879,000 |
When I type the set command in my system I've got this extract out :
__colormgr_commandlist='
create-device
create-profile
delete-device
delete-profile
device-add-profile
device-get-default-profile
device-get-profile-for-qualifier
device-inhibit
device-make-profile-default
devic... |
For the functions, Bash can tell you where they came from:
$ help declare
...
-F restrict display to function names only (plus line
number and source file when debugging)
$ shopt -s extdebug
$ declare -F quote_readline
quote_readline 150 /usr/share/bash-completion/bash_completion
(I found this... | How to know where shell variables and functions are set? |
1,347,105,879,000 |
I'm working on a bash function to check if a tmux session is running. The function works but if no session is running it outputs "failed to connect to server". How do I output that error to null without appending 1>&2 to every function call?
tmux_checker()
{
if [ -z $(tmux ls | grep -o servercontrol) ]
then... |
Redirect the output in the function itself:
tmux_checker()
{
if [ -z $(tmux ls 2>/dev/null | grep -o servercontrol) ]
then
tmux new -d -s servercontrol
fi
}
tmux_checker
| Bash Script Function Output /dev/null |
1,347,105,879,000 |
So I am trying to create a simple function to replace the standard who command with my own, similar to a function I use to replace the standard cd command.
Goal: Replace original who command with who "$@" | fgrep -v <user> in order to hide a user from it.
Similar example:
function cd () {
builtin cd "$@" && ls
}
... |
Like thrig commented, the command to run external commands is command.
Your new function could look like:
function who() {
command who "$@" | fgrep -v user
}
| How do I reference an original command, so I can replace it with a function |
1,430,404,323,000 |
I'm fairly new to bash scripting, and wondered what's the simplest way to make bash script functions in a script as the parameter when run via command line?
Example usage:
./myscript function1
./myscript function2
Example contents of myscript:
echo "Example myscript"
function1() {
echo "I am function number 1"
... |
All arguments passed to shell script was stored in $@, you can loop through them:
#!/bin/bash
echo "Example myscript"
function1() {
echo "I am function number 1"
}
function2() {
echo "I am function number 2"
}
if [ $# -eq 0 ]; then
echo "Specify a function. E.g. function1"
exit 1;
fi
for func do... | What's the best way to make a bash function in a script as a parameter when running via command line? |
1,430,404,323,000 |
I use the expression "overriding wrapper" to refer to a function foo that overrides some original function falls, and calls this original function (or a copy of its) during its execution.
I have found Stack Exchange threads about this (like this one), but in my case I have the additional requirement that both the orig... |
You can use this function to load the code of a function from a file in the same way that autoload does it, without the restriction that the file name has to match the function name.
## load_from FILE FUNCTION_NAME
load_from () {
eval "$2 () { $(<$1) }"
}
Here's how the wrapper code looks like. $^fpath/somefunction... | How to write an "overriding wrapper" for a function in FPATH? |
1,430,404,323,000 |
Hello ALL and thanks in advance.
I have searched the forum for my situation and have been unable to locate a solution. I've got a script that I am passing arguments/options/parameters to at the command line. One of the values has a space in it, which I have put in double quotes. It might be easier to provide an ex... |
Using $* or $@ unquoted never makes sense.
"$*" is the concatenation of the positional parameters with the first character (or byte depending on the shell) of $IFS, "$@" is the list of positional parameters.
When unquoted, it's the same but subject to split+glob (or only empty removal with zsh) like any other unquoted... | Passing options/args/parameters with spaces from the script to a function within |
1,430,404,323,000 |
Want to add a function in the .vimrc to auto get the text between double quotes.
If current line is
add_file -vhdl -lib work "../src/abc.vhd"
The function will get ../src/abc.vhd
|
The straightforward solution is yanking the inner double-quotes text object (as per @muru's comment): First move inside the quote with f", then yi".
Alternatively, you can use lower-level functions to extract a pattern from the current line:
:echo matchstr(getline('.'), '"\zs[^"]\+\ze"')
This doesn't change cursor po... | Vim Function: How to get text between double quotes? |
1,430,404,323,000 |
Bash can print the current function name:
$ bash -c 'g(){ echo $FUNCNAME; }; g'
g
However Dash cannot use FUNCNAME:
$ dash -c 'g(){ echo $FUNCNAME; }; g'
It is possible to access the current function name with Dash?
|
With any POSIX shells:
defun() {
eval "
$1() {
FUNCNAME=$1
$(cat)
}
"
}
defun g <<\}
printf '%s\n' "$FUNCNAME"
}
g
Note that you can't call a function defined by defun inside body of a function defined by defun.
| Bash FUNCNAME equivalent in Dash |
1,430,404,323,000 |
What am I doing wrong...? It's fine if I do this on the command line and then call it but not when I load it from .profile. Linux Mint Qiana, Bash 4.*, if it matters.
function android() { command /opt/android-studio/bin/studio.sh "$@" & disown ; }
export -f android
I've tried shortening the command, extending it... |
Traditionally bash functions are placed in ~/.bashrc as this is read by interactive bashes. ~/.profile is only read by login bashes. New windows usually dont run login bashes.
| Exporting a function from .profile/.bashrc |
1,430,404,323,000 |
I can to define function in bash and use it:
foo() { echo $1; }
foo test
But if I want to collect my functions in one bash script all its unavailable:
init.bash
#!/bin/bash
foo() { echo $1; }
export -f foo # This not helps
Using:
./init.bash && foo test # error here
Is there any way to export script's functions t... |
You could source the file init.sh. No need to export the function in that file.
$ cat init.bash
foo() { echo $1; }
And use it:
$ . ./init.bash && foo test
test
Sourcing a file would execute commands from it in the current shell context. As such, the functions would be available in the parent.
export would set the... | Include a bash function into the parent script |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.