Questions tagged [function]
Questions on function usage in the context of Unix & Linux (mostly but not exclusively shell scripts). Questions on programming in Python, Perl, Ruby, etc. should be asked on Stack Overflow.
583 questions
2
votes
1
answer
102
views
Bash: function in a script with flags
Using https://stackoverflow.com/a/7948533/31298396, we can implement flags for a script testing as follows:
#!/bin/bash
# Flags
# Source: https://stackoverflow.com/a/7948533/31298396
TEMP=$(getopt ...
3
votes
2
answers
149
views
Localising variables in /bin/sh functions
POSIX defines shell functions as:
fname ( ) compound-command [io-redirect ...]
The compound-command is further defined as either:
( compound-list )
{ compound-list ; }
In particular POSIX notes for ...
0
votes
1
answer
69
views
How to keep a local function private in a zsh `autoload` module?
I want to define a helper function in a zsh autoload-ed module. The problem is, if I just define in my my_autoloaded_fn file such as
function helper {
# ...
}
helper a
helper b
the name helper ...
2
votes
4
answers
203
views
Is there a Bash variable containing the name of the previously executed function?
I want to line up a couple of Bash functions based on the success or failure of the execution of the preceding function.
If something fails, I want to print an error message: function_x has failed.
...
0
votes
0
answers
30
views
Why is set -e also ignored for functions called via command substitution [duplicate]
I've seen questions about this topic, but they talk about constructs like if or ||.
I don't understand why the same behavior seem to happen for substitution ($())?
$ my_function() { echo "the ...
4
votes
1
answer
297
views
Run in background avoiding any job control message from the shell [duplicate]
Lets define a shell function (here the shell is Bash) and test it
$ s () { xterm -e sleep 5 & }
$ s
[1] 307926
$
[1]+ Done xterm -e sleep 5
$
With my specific meaning of ...
7
votes
1
answer
609
views
bash - how to remove a local variable (inside a function)
I've read what's listed in Bibliography regarding unset, declare, local and "Shell Functions".
My version of Bash is
GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu)
var='outer'
...
2
votes
1
answer
225
views
Why does a 'pipe-to-awk' behave differently inside a function?
I'm using alsa to fiddle around with the volume on a Bluetooth speaker I have connected. It's a 1-speaker setup; just something to provide some background.
I can 'get' the volume setting fm the CLI as ...
3
votes
1
answer
624
views
Strange variable scope behavior when calling function recursivly
EDIT: sorry. this is my first question here.
Here is a minimal working example
#!/bin/bash
#
count=0
function something() {
if test -f "$1"; then
# is a file
((count++))
...
-1
votes
1
answer
188
views
Override tr in ~/.bashrc
I'm trying to create a function to translate words via a custom script:
function mean() {
~/scripts/translate.sh $1
}
I would prefer the function to be named tr, as it is much shorter and faster ...
3
votes
1
answer
347
views
How to overload / customize bash (or any other shell) commands handler?
When in bash some non existing command is run, corresponding error message appears:
$ non-existent-command
non-existent-command: command not found
Is it possible to customize this behavior?
I would ...
3
votes
2
answers
400
views
how to alias the `history` function in fish shell
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 &...
0
votes
2
answers
110
views
Bash scripting: When to use variable, when function?
basic, innocent question:
In bash scripting, why ever using a function, if one can set a variable containing command substitution with the essence of the function - a certain command or set of ...
2
votes
0
answers
48
views
Can't unalias then redefine as a function in the same conditional [duplicate]
Here is a simplified implementation of an issue in my bash/zsh aliases file:
alias foobar='echo bar' # this is out of my control
if true; then
unalias foobar
echo we got inside the conditional
...
1
vote
1
answer
2k
views
How to get function keys working on a Yunzii keyboard?
I have a Yunzii B705 keyboard. It has a row of multimedia keys that double as the function keys. Neither the multimedia nor function keys can work. I don't care about using the multimedia functions, ...
0
votes
4
answers
1k
views
return value of a function
Can somebody explain me, why the return value of a bash function is always echoed in the function and then consumed by my_var=$(my_func arg1 arg2 ..), when i look through code examples.
my_func ()
{...
3
votes
1
answer
115
views
How does my function break `functions`?
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
...
1
vote
2
answers
148
views
Start interactive function definition from shell-script
Using zsh or bash, I want to run a script that may prompt the user for multiple commands and store them as a function, however I'm finding that eval "function $FNCNAME() {" or echo "...
1
vote
3
answers
536
views
Run nested local bash functions via ssh
I have a script like this that declares many functions which use another functions, etc.:
#!/bin/bash
function a {
...
}
function b {
...
a
...
}
...
And another script that uses ...
0
votes
1
answer
430
views
how to write function with nested commands [duplicate]
I'm trying to write a find and cd function like so:
findcd () {
cd "$(dirname "$(find '$1' -type '$2' -name '$3')")"
}
to be called like so:
find . f [FILE_NAME]
But it's ...
1
vote
1
answer
294
views
Run `git commit -m` with single quotes in zsh
I sometimes use characters such as ! and $ in commit messages, they need to be manually escaped, but not if you use single quotes like this git commit -m 'My $message here!'. I tried to write a ...
1
vote
2
answers
166
views
String Length Always Returns 2 in ZSH Function
I'm trying to bowdlerize email addresses in a fixed length text file by generating a random string the same length as the input. I'm passing the string as a backreference in sed.
To simplify, this ...
0
votes
3
answers
1k
views
Does `return 0` equal `true` (in sourced script to shell's environment)?
I am working on a highly portable script that users shall source to their shells, forcing me to use POSIX scripting.
There are many useful functions in the script, one of them is special though, as ...
0
votes
1
answer
325
views
How to store command with option on variable of a function in zsh?
I'm trying to learn bash scripting using freeCodeCamp tutorial for beginners on YouTube.
I'm stuck at the point where he shows how to create a function.
He saved on a variable a command with an option
...
0
votes
1
answer
739
views
Running a function as process with a set process name or id
I have a bash script set up to monitor a number of UDP streams and convert it into actionable data. My problem is that I need to set the script to periodically check to see if the stream capture is ...
2
votes
4
answers
357
views
Function's comment is not printed out when putting it before the function's header
A good and well-established guideline for commenting a shell function is to put it before the function's header. I am trying to follow these guidelines as much as I can, but this convention makes it ...
0
votes
2
answers
245
views
How we can recursively expand inline functions and aliases inside function?
Nesting problem with duck typing:
function f1 { echo $1; } #with argument
function f2 { N=$((0+1)); f$N "fff"; } #with dynamic name
Desired result:
function f2 { { echo $1; } "fff"...
0
votes
1
answer
146
views
BASH: use . instead of a space for command completion
I have bash function directory located at /git/function
This is structure:
/git/function/
├── delete
│ ├── delete.dir
│ └── delete.file
├── main.sh
├── get
│├── get.dir.sh
│└── get.file.sh
How to use ...
0
votes
0
answers
41
views
printf and echo -n Work Differently - Why? [duplicate]
echo -n
my_function() {
echo -n "$@"
}
my_function hello world
I get my desired output:
hello world
printf
my_function() {
printf "$@"
}
my_function hello world
I get only ...
0
votes
2
answers
96
views
> symbol appearing when interactively defining function in bash
The behaviour of my shell environment changed:
Earlier, when pasting a function definition e.g.
function exampleFunc {
echo hello
}
to the shell, it would display as formatted and register the ...
0
votes
1
answer
138
views
Bash create parameter named array within function
I'm attempting to write a function that writes arrays with a name that's passed in. Given the following bash function:
function writeToArray {
local name="$1"
echo "$name"
...
2
votes
1
answer
385
views
printf "%.3f" ${variable with newlines} - error with \n
Like HERE I have a file.csv with numbers in quotes:
"0.2"
"0.3339"
"0.111111"
To round the number (3 decimals) this solutions works great:
printf "%.03f\n" $(...
0
votes
2
answers
110
views
How to add corresponding strings to a file from another file that it shares a field with?
I have two files that both have the field "tumor id". Both are comma delimited. I need to add a field that is uniquely in file 2 to file 1, and I want to add the lines of the field according ...
0
votes
1
answer
183
views
Processing a multiline variable line by line within a bash function
Is it possible to process a multiline variable in a bash function? Suppose I have a function theone and I pass a multiline variable to it.
var="
This
is a
multiline
variable"
theone "...
0
votes
1
answer
9k
views
How to return from bash functions the right way?
This script, which i source in my terminal, offers the function _cphetzner, that is used to create a git repository. This function uses another function _feed_variable that prompts user for missing ...
0
votes
2
answers
64
views
How to pass commands around?
I have this simple script, which does nothing more than:
check if an email matches a specific pattern
in that case, add a tag to a taglist
before quitting, print that taglist
set -e
lista_tag=()
...
-1
votes
2
answers
4k
views
Local variables in bash functions
I am getting confused about setting local variables in bash functions.
It seems that using
local dgt
local ltr
local braces
local da
could be safer than using
local dgt ltr braces da
I am ...
0
votes
1
answer
32
views
function that allows different outputs dependent on argument values
With the following function I want to be able to call it
with nico-usage or with a numeric value to print a different string.
Con this be cleaned up or made easier.
nico-usage ()
{
local ...
1
vote
1
answer
354
views
How to write a function that takes an argument string that does not need to be quoted?
I'm writing a function, adding it to ~/.zshrc on my Mac. It's in order to more quickly handle commands to youtube-dl.
I have this:
function dlv()
{
cd /Users/admin/Downloads
youtube-dl ...
0
votes
2
answers
95
views
Shell function to center its first argument
In the nano text editor, I can pipe the selection into a command, and I quite often need to center text, so I came up with the following code
center() {
str=$1
# Strip leading and trailing ...
4
votes
1
answer
242
views
Why do backgrounded commands in Zsh functions not show correctly in jobs?
In Bash 5.2, the output of jobs after either of the following is identical modulo job numbers:
sleep 3
# press C-z
s() { sleep 3; }
s
# press C-z
In both, jobs produces something like
[1]+ Stopped ...
1
vote
0
answers
112
views
Avoiding support bash functions to show up in terminal sessions when tab-completing
I have a number of bash functions which I source from my .bashrc. I also have a bunch of support function that are needed but do not want them to show up in a terminal session when a user does tab-...
0
votes
2
answers
309
views
Compare Execution Times of Two Functions
I am attempting to write a function which will take two commands as inputs, time the executions of both of them, then output those times to a text file. After reading this post, I got most of the way ...
1
vote
0
answers
101
views
startx function/alias has wrong arguments if not prefixed with exec
For context, my file/directory structure and contents are mostly copied from how it is in Luke Smith's dotfiles (voidrice). Also, the "..." lines in the code blocks aren't code and represent ...
0
votes
0
answers
10
views
Linux regex in substitution of a string passing argument from CLI [duplicate]
I have wrote the simple script
#!/bin/bash
progname=$1
sed -i.bak 's/#define SFFX "_.*"/#define SFFX "_$progname"/' path/to/file
In order to find a preprocessor directive in a C ...
1
vote
1
answer
168
views
Bash Function Grep Mod
TL:DR How do I add a grep to a bash function while allowing a variable number of optional inputs?
I find that in repeated grepping of large outputs, I end up clogging the terminal with data. ...
1
vote
2
answers
2k
views
How can I/Should I default flags when running a command?
For context, I'm using zsh. Every time I use locate, I want to pass the -i and -A flags.
Usually, if I can get away with it, I create an alias with the same name as the existing command to do this. ...
5
votes
4
answers
822
views
How can I make time measurement DRY in my bash scripts?
Based on this answer, to measure the time in my bash scripts I can use:
start_time="$(date -u +%s.%N)"
sleep 5
end_time="$(date -u +%s.%N)"
elapsed="$(bc <<<"$...
1
vote
2
answers
609
views
zsh: alias or shell function to only echo its command line, including shell control characters
Using zsh, I'd like to create an alias or a shell function that operates as follows:
I want this alias or shell function to echo its command line without honoring any shell control characters such as &...
0
votes
2
answers
150
views
Using bash return depending on return status of last command executed within a function
I have the following bash function that returns 0 when tho variable verbos is defined. Have read the bash manual which says that when return command return N, the N is omitted, the return status is ...