Unix & Linux Stack Exchange
Q&A for users of Linux, FreeBSD and other Unix-like operating systems
Latest Questions
2
votes
1
answers
3305
views
Run executable on background detached from terminal but with arguments
I can run an executable in the background and detach it from the terminal with these commands: $ nohup ./executable & or $ ./executable & $ disown But none work if I send arguments to the executable: $ nohup ./executable argument & or $ ./executable argument & $ disown I have tried combining it with...
I can run an executable in the background and detach it from the terminal with these commands:
$ nohup ./executable &
or
$ ./executable &
$ disown
But none work if I send arguments to the executable:
$ nohup ./executable argument &
or
$ ./executable argument &
$ disown
I have tried combining it with the .sh strings and pipes syntax but it does not work either:
$ nohup ./executable <<<$'argument' &
or
$ ./executable <<<$'argument' &
$ disown
or
$ nohup echo -e "argument" | ./executable &
or
$ echo -e "argument" | ./executable &
$ disown
EDIT: The "./executable" program accepts any number of parameters, like "./executable arg1 arg2" etc... I think the problem is that "&" gets absorbed by "./executable" as a parameter. Also, it is written in Go if that is of any help.
Azkron
(21 rep)
Apr 21, 2021, 09:43 PM
• Last activity: May 23, 2025, 01:07 AM
1
votes
4
answers
140
views
Need shell script help - processing the same option multiple times
So I've ran into a bit of a wall, I have an option in my script that calls a function which allows me to specify a file/directory and then I want to parse that output into a menu tool (using dmenu in this case) to select which file is the one I want specifically and continue working with that select...
So I've ran into a bit of a wall, I have an option in my script that calls a function which allows me to specify a file/directory and then I want to parse that output into a menu tool (using dmenu in this case) to select which file is the one I want specifically and continue working with that selection as a variable
in the same script. This works fine if it's just one file or directory, but I want to be able to use the option multiple times and then parse all of that output at once to dmenu. Here's a snippet
fileSelection () {
if [ -d "${OPTARG}" ]; then find "${OPTARG}" -type f; fi;
if [ -f "${OPTARG}" ]; then printf '%s\n' "${OPTARG}"; fi;
}
while getopts "f:" option; do
case "${option}" in
f) file="$(fileSelection|dmenu)";;
esac
done
And like I said this works if I do:
myscript -f file
or
myscript -f directory
but I was hoping to also be able to do this:
myscript -f file1 -f file2
The problem is, since the function is called consecutively I can't parse the output into dmenu like that, because it doesn't invoke dmenu with options file1 and file2, but first with file1 and then with file2, I hope this makes sense.
There might be some really simple solution I am missing, I've thought about simply writing the output into a file and then parsing that which might work, but I'd like to avoid piping to files if possible. I am also trying to keep it POSIX compliant, and would appreciate answers that follow that.
hollowillow
(11 rep)
Mar 18, 2025, 10:09 PM
• Last activity: Mar 20, 2025, 07:58 PM
4
votes
5
answers
23285
views
Argument list too long error with makefile
In a makefile, I have @echo "$(IGNORE_DIRS) $(CLEAN_FILES) $(CLEAN_DIRS) $(REALCLEAN_FILES)" | tr ' ' '\n' >> $@ The problem is that `$(CLEAN_FILES)` is quite large, so when I run make, I get make: execvp: /bin/sh: Argument list too long I'm on Xubuntu 18.10. Edit: I should provide a little more con...
In a makefile, I have
@echo "$(IGNORE_DIRS) $(CLEAN_FILES) $(CLEAN_DIRS) $(REALCLEAN_FILES)" | tr ' ' '\n' >> $@
The problem is that
$(CLEAN_FILES)
is quite large, so when I run make, I get
make: execvp: /bin/sh: Argument list too long
I'm on Xubuntu 18.10.
Edit: I should provide a little more context. What I am working on is a make rule (I'm using GNU make) to automatically generate the .hgignore
file. Here is the make rule in its entirety:
.hgignore : .hgignore_extra
@echo "Making $@"
@rm -f $@
@echo "# Automatically generated by Make. Edit .hgignore_extra instead." > $@
@tail -n +2 $> $@
@echo "" >> $@
@echo "# The following files come from the Makefile." >> $@
@echo "syntax: glob" >> $@
@echo "$(IGNORE_DIRS) $(CLEAN_FILES) $(CLEAN_DIRS) $(REALCLEAN_FILES)" | tr ' ' '\n' >> $@
@chmod a-w $@
.PHONY : .hgignore
Edit 2: At @mosvy 's suggestion, I have also tried
.hgignore : .hgignore_extra
@echo "Making $@"
@rm -f $@
@echo "# Automatically generated by Make. Edit .hgignore_extra instead." > $@
@tail -n +2 $> $@
@echo "" >> $@
@echo "# The following files come from the Makefile." >> $@
@echo "syntax: glob" >> $@
$(file >$@) $(foreach V,$(IGNORE_DIRS) $(CLEAN_FILES) $(CLEAN_DIRS) $(REALCLEAN_FILES),$(file >>$@,$V))
@true
@chmod a-w $@
.PHONY : .hgignore
Running make .hgignore
with this, I no longer get the "Argument list too long" error, but the generated .hgignore file only contains output up to the syntax: glob
line, and then nothing after that.
teerav42
(159 rep)
Nov 9, 2018, 01:51 AM
• Last activity: Mar 20, 2025, 04:09 PM
136
votes
10
answers
216183
views
Solving "mv: Argument list too long"?
I have a folder with more than a million files that needs sorting, but I can't really do anything because `mv` outputs this message all the time -bash: /bin/mv: Argument list too long I'm using this command to move extension-less files: mv -- !(*.jpg|*.png|*.bmp) targetdir/
I have a folder with more than a million files that needs sorting, but I can't really do anything because
mv
outputs this message all the time
-bash: /bin/mv: Argument list too long
I'm using this command to move extension-less files:
mv -- !(*.jpg|*.png|*.bmp) targetdir/
Dominique
(5465 rep)
May 8, 2014, 11:31 PM
• Last activity: Mar 17, 2025, 10:02 AM
1
votes
3
answers
6357
views
Passing options to cmake in bash script
I am trying to write a script that will build multiple cppUtes lib.a files for different sanitizers with a bash script. When trying to pass the compiler flags as variables to cmake I am unable to correctly format them. Please see the brief example below. ```bash #!/bin/sh set -euo pipefail COMMON_OP...
I am trying to write a script that will build multiple cppUtes lib.a files for different sanitizers with a bash script.
When trying to pass the compiler flags as variables to cmake I am unable to correctly format them. Please see the brief example below.
#!/bin/sh
set -euo pipefail
COMMON_OPTS='-fno-common -g -fno-omit-frame-pointer'
ASAN_OPT='-fsanitize=address'
ASAN_C_FLAGS="-DCMAKE_C_FLAGS=\"$ASAN_OPT $COMMON_OPTS\""
echo "cmake ../ $ASAN_C_FLAGS"
cmake ../ $ASAN_C_FLAGS
make
The output of echo is what I expect, and what works for setting flags when not running in a bash script:
cmake ../ -DCMAKE_C_FLAGS="-fsanitize=address -fno-common -g -fno-omit-frame-pointer"
However, when I run the script cmake is not interpreting the flags correctly. They do not appear in the cmake flags that are displayed during the configuration:
CppUTest CFLAGS: -include "/home/ubuntu/cpputest/include/CppUTest/MemoryLeakDetectorMallocMacros.h" -Wall -Wextra -pedantic -Wshadow -Wswitch-default -Wswitch-enum -Wconversion -Wsign-conversion -Wno-padded -Wno-long-long -Wstrict-prototypes
and finally, I get the following compilation error from make:
c++: error: unrecognized argument to '-fsanitize=' option: 'address -g -fno-omit-frame-pointer'
Any help would be kindly appreciated.
Buoy
(111 rep)
Jan 8, 2020, 02:05 AM
• Last activity: Feb 25, 2025, 04:14 PM
5
votes
4
answers
882
views
Pass multiple files as a single option
I'm trying to build a wrapper to execute a tool multiple times, then concatenate some of the results. I'd like to pass two sets of files to my wrapper script, then run the tool for each pair of files. I'd like it to behave like this: `multitool.sh -a a*.txt -b b*.txt` (expanding the wildcards to mat...
I'm trying to build a wrapper to execute a tool multiple times, then concatenate some of the results. I'd like to pass two sets of files to my wrapper script, then run the tool for each pair of files. I'd like it to behave like this:
multitool.sh -a a*.txt -b b*.txt
(expanding the wildcards to match all files available)
Then inside multitool.sh
, I run the tool on a1.txt b1.txt
, a2.txt b1.txt
, a1.txt b2.txt
, a2.txt b2.txt
, etc, with variable numbers of a and b files.
I followed [this](https://www.redhat.com/en/blog/arguments-options-bash-scripts) tutorial explaining the basics of option handling, and I'm able to use getops
to handle a -h
, but nothing else.
Here is where I'm at now:
#!/bin/bash
while getopts ":hpg:" option; do
case $option in
h) # display help
echo "-h to print this help and exit, -p is peak files, -g is bedgraph files."
exit;;
p) # get list of peak files to process
l_peaks=$OPTARG;;
g) # get list of bedgraph files to process
l_bgraphs=$OPTARG;;
\?) # Invalid option
echo "Error! Invalid option!"
echo "-h to print this help and exit, -p is peak files, -g is bedgraph files."
exit;;
esac
done
echo "$l_peaks"
echo "$l_bgraphs"
I'm working with a team who aren't particularly computer literate, so if I can keep the wrapper to a simple one line execution, that would be best.
How can I pass these lists of files as one option each?
Whitehot
(245 rep)
Feb 24, 2025, 01:09 PM
• Last activity: Feb 25, 2025, 07:08 AM
2
votes
2
answers
2630
views
Passing options/args/parameters with spaces from the script to a function within
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 example. Forgive my usage of arguments/options/parameters. $: ./test1.ksh -n -b -d "Home Videos" My proble...
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 example. Forgive my usage of arguments/options/parameters.
$: ./test1.ksh -n -b -d "Home Videos"
My problem is setting a variable to "Home Videos" and it being used together. In my example, the -d is to specify a directory. Not all the directories have spaces, but some do in my case.
This is an example of the code I have that is not working as expected:
#!/bin/ksh
Function1()
{
echo "Number of Args in Function1: $#"
echo "Function1 Args: $@"
SetArgs $*
}
SetArgs()
{
echo -e "\nNumber of Args in SetArgs: $#"
echo "SetArgs Args: $@"
while [ $# -gt 0 ]
do
case $1 in
-[dD])
shift
export DirectoryName=$1
;;
-[nN])
export Var1=No
shift
;;
-[bB])
export Var2=Backup
shift
;;
*)
shift
;;
esac
done
Function2
}
Function2()
{
echo "Directory Name: ${DirectoryName}"
}
Function1 $*
When I run this, I'm getting only Home for the DirectoryName instead of Home Videos. Seen below.
$ ./test1.ksh -n -b -d "Home Videos"
Number of Args in Function1: 5
Function1 Args: -n -b -d Home Videos
Number of Args in SetArgs: 5
SetArgs Args: -n -b -d Home Videos
Var1 is set to: No
Var2 is set to: Backup
Directory Name: Home
What I am expecting and I have not been able to get it to happen is:
$ ./test1.ksh -n -b -d "Home Videos"
Number of Args in Function1: 4
Function1 Args: -n -b -d "Home Videos"
Number of Args in SetArgs: 4
SetArgs Args: -n -b -d "Home Videos"
Var1 is set to: No
Var2 is set to: Backup
Directory Name: Home Videos <-- Without double quotes in the final usage.
I've tried escaping the double quotes, without any success.
DNadler
(23 rep)
Nov 21, 2017, 11:05 AM
• Last activity: Dec 31, 2024, 10:23 AM
0
votes
2
answers
610
views
Why do these rsync filter args fail in bash when passed in array?
Why does this rsync command work when I give it literally but not when I create it from variables? Here are the variables - first the options I'm passing to rysnc, as an array: $ echo "${options[@]}" -av --prune-empty-dirs -f "- *.flac" -f "- *.WMA" -f "- *.wma" -f "- *.ogg" -f "- *.mp4" -f "- *.m4a...
Why does this rsync command work when I give it literally but not when I create it from variables?
Here are the variables - first the options I'm passing to rysnc, as an array:
$ echo "${options[@]}"
-av --prune-empty-dirs -f "- *.flac" -f "- *.WMA" -f "- *.wma" -f "- *.ogg" -f "- *.mp4" -f "- *.m4a" -f "- *.webm" -f "- *.wav" -f "- *.ape" -f "- *.zip" -f "- *.rar"
$ echo ${options}
-f
$ echo ${options}
"- *.wma"
Then the source directory, from which rsync is to copy files:
$ echo "\"$dir/\""
"/media/test/Ahmad Jamal Trio/Live at the Pershing/"
And the target directory, to which rsync is to copy files:
$ echo "\"$target_dir\""
"/home/test/mp3/Ahmad Jamal Trio/Live at the Pershing/"
Put it all together:
$ echo "${options[@]}" "\"$dir/\"" "\"$target_dir\""
-av --prune-empty-dirs -f "- *.flac" -f "- *.WMA" -f "- *.wma" -f "- *.ogg" -f "- *.mp4" -f "- *.m4a" -f "- *.webm" -f "- *.wav" -f "- *.ape" -f "- *.zip" -f "- *.rar" "/media/test/Ahmad Jamal Trio/Live at the Pershing//" "/home/test/mp3/Ahmad Jamal Trio/Live at the Pershing/"
That all looks like it should. And indeed, it does work if you give the command literally, like this:
$ rsync -av --prune-empty-dirs -f "- *.flac" -f "- *.WMA" -f "- *.wma" -f "- *.ogg" -f "- *.mp4" -f "- *.m4a" -f "- *.webm" -f "- *.wav" -f "- *.ape" -f "- *.zip" -f "- *.rar" "/media/test/Ahmad Jamal Trio/Live at the Pershing/" "/home/test/mp3/Ahmad Jamal Trio/Live at the Pershing/"
./
Ahmad Jamal Trio - Live at the Pershing - 01 - But Not for Me.mp3
Ahmad Jamal Trio - Live at the Pershing - 02 - Surrey With The Fringe On Top.mp3
Ahmad Jamal Trio - Live at the Pershing - 03 - Moonlight In Vermont.mp3
Ahmad Jamal Trio - Live at the Pershing - 04 - Music, Music, Music.mp3
Ahmad Jamal Trio - Live at the Pershing - 05 - No Greater Love.mp3
Ahmad Jamal Trio - Live at the Pershing - 06 - Poinciana.mp3
Ahmad Jamal Trio - Live at the Pershing - 07 - Wood'yn You.mp3
Ahmad Jamal Trio - Live at the Pershing - 08 - What's New.mp3
AlbumArtSmall.jpg
AlbumArtLarge.jpg
Folder.jpg
sent 43,194,376 bytes received 285 bytes 28,796,440.67 bytes/sec
total size is 43,182,454 speedup is 1.00
But it fails when I call rsync using the vars as args:
$ rsync "${options[@]}" "\"$dir/\"" "\"$target_dir\""
Unknown filter rule: `"- *.flac"'
rsync error: syntax or usage error (code 1) at exclude.c(902) [client=3.1.2]
markling
(231 rep)
Nov 5, 2019, 10:40 AM
• Last activity: Dec 29, 2024, 11:04 AM
2
votes
0
answers
47
views
In the context of {ARG_MAX}, how robust is `find . -exec sh -c 'exec tool "$@" extra-arg' find-sh {} +`?
Suppose I want to do this: find . -exec tool {} extra-arg + It doesn't work and I know why: `-exec … {} +` does not allow `extra-arg`(s) between `{}` and `+`. So be it. It seems I can inject the `extra-arg` by using a shell, like this: find . -exec sh -c 'exec tool "$@" extra-arg' find-sh {} + My qu...
Suppose I want to do this:
find . -exec tool {} extra-arg +
It doesn't work and I know why:
-exec … {} +
does not allow extra-arg
(s) between {}
and +
. So be it. It seems I can inject the extra-arg
by using a shell, like this:
find . -exec sh -c 'exec tool "$@" extra-arg' find-sh {} +
My question is: **how robust is this method?** I mean in the context of {ARG_MAX}
and possible "argument list too long" error. I know find … -exec … {} +
is supposed to group pathnames in sets to avoid the error. At first glance the command from the expansion of tool "$@" extra-arg
should be shorter than what find
executes, so if find
manages to avoid "argument list too long" then exec tool …
will avoid it as well; but:
1. I'm not sure if the relevant structure will contain tool
or /full/absolute/path/to/tool
which may be long and thus possibly make the structure exceed {ARG_MAX}
, despite the effort to not exceed {ARG_MAX}
taken by find
earlier.
0. I'm not sure if sh
may add something to the relevant structure and thus possibly make the structure exceed {ARG_MAX}
, despite the effort to not exceed {ARG_MAX}
taken by find
earlier.
**Assuming that find
does a good job avoiding "argument list too long", can I assume my exec tool …
invoked in the inner shell will avoid the error as well?**
Clarification:
- Yes, I'm asking about my attempted solution, like in the XY problem; but I'm *deliberately* asking about my attempted solution because I want to understand possible flaws of it. I know I can use -exec tool {} extra-arg \;
and avoid the problem. I know I can pipe (preferably null-terminated strings) to xargs
and let xargs
deal with {ARG_MAX}
. If my attempted solution is not robust and if some improvement can make it robust then I'm interested, but only if -exec … {} +
is kept.
- I know that some implementations of find
do not try to get as close to {ARG_MAX}
as possible , but according to the POSIX specification find
does not have to leave any room we could take advantage of later. I do not have any particular implementation of find
in mind. In this matter I will appreciate generic answers or answers that compare many implementations.
- In the context of (1), the question is specifically about Linux. If a good answer mentions or compares to other Unices then fine, I don't mind extending the scope this way; but I do not require this.
- In the context of (2), I do not have any particular implementation of sh
in mind.
Kamil Maciorowski
(24294 rep)
Nov 28, 2024, 01:45 PM
21
votes
3
answers
46540
views
Is there an easy way to log all commands executed, including command line arguments?
I am trying to find how to log a specific instantiation of `rrdtool` to see whether the path it is receiving is incorrect. I know I could wrap the executable in a shell script that would log the parameters, but I was wondering if there was a more kernel-specific way to monitor for that, perhaps a fi...
I am trying to find how to log a specific instantiation of
rrdtool
to see whether the path it is receiving is incorrect.
I know I could wrap the executable in a shell script that would log the parameters, but I was wondering if there was a more kernel-specific way to monitor for that, perhaps a filesystem callback that sees when a particular /proc/pid/exe matches a given binary?
Peter Grace
(747 rep)
Jul 29, 2013, 10:21 PM
• Last activity: Nov 7, 2024, 09:36 AM
0
votes
1
answers
51
views
Can we pass directory list from find command as argument to another find command and execute md5sum?
I want to list all the directories in present directory and pass those directories as a argument to another find command The below example will explain it correctly. ``` $ find . -maxdepth 1 -type d . ./dir1 ./dir2 ./dir3 ./dir4 $ echo -e "\n" ; find (above directories as argument) -exec md5sum {} +...
I want to list all the directories in present directory and pass those directories as a argument to another find command
The below example will explain it correctly.
$ find . -maxdepth 1 -type d
.
./dir1
./dir2
./dir3
./dir4
$ echo -e "\n" ; find (above directories as argument) -exec md5sum {} +
So that I get checksum values for every files in a folder separately, separated by space.
I think the above example explains the problem correctly Sorry for my bad English and I have very little knowledge on Linux command please forgive me
Thank you in advance.
user27072144
(1 rep)
Oct 5, 2024, 09:58 AM
• Last activity: Oct 5, 2024, 01:28 PM
1
votes
2
answers
23106
views
open eclipse from a terminal and pass a workspace to open
I want to open eclipse through terminal and i am able to do it, but when when eclipse starts it asks for the workspace directory attached the screenshot,and then there i have to specify it, i dont want this. [![enter image description here][1]][1] As i pass the **eclipse** command in the terminal, i...
I want to open eclipse through terminal and i am able to do it, but when when eclipse starts it asks for the workspace directory attached the screenshot,and then there i have to specify it, i dont want this.
As i pass the **eclipse** command in the terminal, i want to pass the workspace directory along with the eclipse command followed by **OK** as prompt ask for it.
Thanks in advance.

Taleev Aalam
(23 rep)
Jan 3, 2018, 02:09 PM
• Last activity: Sep 26, 2024, 09:46 AM
11
votes
1
answers
962
views
Confusion about changing meaning of arguments and options, is there an official standard definition?
I came across a confusing variation in the understanding what options and arguments are with regard to the syntax of commands. For instance, I encountered definitions like: - `command -a -b -c d e f` some differ between `-a -b -c`, call them options or switches and `d e f` by calling them arguments....
I came across a confusing variation in the understanding what options and arguments are with regard to the syntax of commands.
For instance, I encountered definitions like:
-
command -a -b -c d e f
some differ between -a -b -c
, call them options or switches and d e f
by calling them arguments.
- command -a -b -c d e f
some, for instance a bash
manual, call all -a -b -c d e f
arguments and explains, that all of them are accessible from a script by $1 $2 $3 $4 $5 $6
respectively.
- command -a b=c
some call -a
an option, b
an argument and c
the value, but others mix them like in the first two points, in one variety calling all -a b c
arguments.
Those three versions are only examples for a plethora of different calling varieties, I do not even know how to list them all, but I noticed that for sure there is no fixed naming convention.
Or at least, there is no standardised naming convention I know about, because I came across different random sources, but even among official Linux and GNU affiliated sites or manuals I could met this inconsistency.
Is there a unquestionable official naming scheme I can refer to?
sharkant
(3810 rep)
May 11, 2017, 10:30 AM
• Last activity: Aug 20, 2024, 06:00 AM
2
votes
6
answers
2619
views
Applying commands to lists
Very often I need to apply a certain simple function to a list (or more precisely to a string where substrings that I want to treat as separate items are delimited by a new line). Say I need to extract certain numbers from a list of filenames of files containing a certain other string, say `stringTo...
Very often I need to apply a certain simple function to a list (or more precisely to a string where substrings that I want to treat as separate items are delimited by a new line). Say I need to extract certain numbers from a list of filenames of files containing a certain other string, say
stringToBeSearched
. A simple solution to get the appropriate list of file names would be
grep -l "stringToBeSearched" *
I then simply want to feed this to another function that takes the substring I want. To try to do this I define for example
f () { echo $(sed 's/begin-\([0-9]*\).end/\1/' <<<$1) ;}
which should extract digits in a file of for example the format begin-123.end
. I would already prefer to avoid defining such a function at all since it won't be reused, but I can't seem to find the equivalent of what in Mathematica would be called Pure Functions, i.e. something of the form #1 +#2 & for a anonymous function to add two arguments together.
Applied to a string this function does what I want so the only step remaining is to apply it to the correct list of strings. I thought I would be able to do this using
grep -l "stringToBeSearched" * | xargs -n1 f
Only this does not seem to work because xargs does not know the function f. The wrong scope I guess. The solution is suggest to be exporting f (https://stackoverflow.com/a/11003457/7238575) , but that does not seem to help. Others (https://stackoverflow.com/questions/11003418/calling-shell-functions-with-xargs) suggest we also need to call a new instance of bash.
However, if I try
grep -l "stringToBeSearched" * | xargs -n1 bash -c f
it only prints a list of white lines.
Clearly, there must be a much simpler way to do something as simple as applying a function f to a list.
---
Example input and output:
There are some files containing the text stringToBeSearched
. Say one named begin-1.end
and one named begin-2.end
. Say these files are hidden among files not containing stringToBeSearched
. I want to obtain a list of the numbers in the filenames of those files that do contain stringToBeSearched
. So in this case I want to obtain a list containing 1 and 2. Ideally I also have an easy way to apply a function not mentioned above say f2
to these functions. So that in the end I want to be able to run f2 1
and 'f2 2
.
---
If this is an XY problem I would appreciate an answer explaining why this is not the method at all more than the answer to the technical problem. The main point of the question is not how to find these numbers I am looking for (although I would like an answer to that too). It is to ask what the general method of applying a function to a list is. The specific problem explained above is just one instance of the kind of problem where I require the operation of applying a function to a list. It is meant to illustrate the problem of not being able to apply a function to the list. It is not the main problem itself.
Kvothe
(453 rep)
Sep 23, 2019, 04:01 PM
• Last activity: Aug 1, 2024, 05:02 PM
0
votes
1
answers
142
views
Manipulating arguments with OPTIND, OPTARG, getopts, and shift correctly
My small POSIX shell scripts do not usually take any arguments, so this is kind of new to me... The minimal snippet would probably look like this: ```sh # default for hotkey variable on top of script is set hotkey=Print ... while getopts ':hk:' option; do case "$option" in k) # override default hotk...
My small POSIX shell scripts do not usually take any arguments, so this is kind of new to me...
The minimal snippet would probably look like this:
# default for hotkey variable on top of script is set
hotkey=Print
...
while getopts ':hk:' option; do
case "$option" in
k) # override default hotkey variable with supplied arg.
hotkey=$OPTARG
shift 2
;;
h) # self-explanatory I assume, prints usage, and exits script with code 0
print_usage_and_exit 0
;;
*) # inspects unspecified arguments, prints usage, and exits script with code 1
dump_args "$@"
print_usage_and_exit 1
;;
esac
done
...
What remains unclear to me, if in this particular case, there is any use for the notoriety known command:
shift $(( OPTIND - 1 ))
Thanks for any direction
Vlastimil Burián
(30505 rep)
Jun 16, 2024, 04:10 PM
• Last activity: Jul 23, 2024, 02:39 PM
1
votes
1
answers
166
views
How Can I Add Short Arguments to a Shell Script
To add options, I have the following in one of my scripts: ```sh parse_opts() { while [ $# -gt 0 ]; do case "$1" in -h|--help) help=1 shift ;; -r|--raw) raw=1 shift ;; -c|--copy) copy=1 shift ;; -s|--sensitive) sensitive=1 shift ;; -i|--insensitive) insensitive=1 shift ;; *) shift ;; esac done } ```...
To add options, I have the following in one of my scripts:
parse_opts() {
while [ $# -gt 0 ]; do
case "$1" in
-h|--help)
help=1
shift
;;
-r|--raw)
raw=1
shift
;;
-c|--copy)
copy=1
shift
;;
-s|--sensitive)
sensitive=1
shift
;;
-i|--insensitive)
insensitive=1
shift
;;
*)
shift
;;
esac
done
}
There is only one problem, I cannot use multiple options at the same time. For example, using -r -s
works but using -rs
does not. How can I programmatically make it work without adding separate entries? The shell I am using is sh.
Amarakon
(373 rep)
Jul 5, 2022, 06:56 AM
• Last activity: Jun 6, 2024, 11:49 AM
0
votes
1
answers
52
views
getopt with several `--`
I have a script with this usage: ``` myscript [options] positional-args... -- [fwd-params] ``` Because `[options]` can have long, or short variants, I like using `getopt`. But I'm having troubles. I use `getopt` like this: ``` args=$(getopt -o a:,b --long alpha:,gamma -- "$@") eval set -- "$args" wh...
I have a script with this usage:
myscript [options] positional-args... -- [fwd-params]
Because [options]
can have long, or short variants, I like using getopt
. But I'm having troubles.
I use getopt
like this:
args=$(getopt -o a:,b --long alpha:,gamma -- "$@")
eval set -- "$args"
while : ; do
case "$1" in
-a | --alpha) a="$2" ; shift 2 ;;
-b ) b=true ; shift ;;
--gamma ) g=true ; shift ;;
-- ) shift ; break ;;
esac
done
positionals=()
while [ $# -gt 0 ] ; do
case "$1" in
* ) positionals+=("$1"); shift ;;
-- ) shift ; break ;;
esac
done
# What-ever is left in "$@" needs to be forwarded to another program
backend "$@"
This works great if I don't have any [fwd-params]
:
$ getopt -o a:,b -- -a 1 -b pos1 pos2
-a '1' -b -- 'pos1' 'pos2'
^-- getopt adds this to help me find
the end-of-options/start-of-positionals
But it falls apart if the user defined any [fwd-params]
. Here's my desired output:
$ getopt -o a:,b -- -a 1 -b pos1 pos2 -- fwd1
-a '1' -b -- 'pos1' 'pos2' '--' 'fwd1'
^
\- I'll use this to delimit
the positional arguments
from the forwarding ones.
And here's what I actually get. The user's intentional --
has been filtered out.
$ getopt -o a:,b -- -a 1 -b pos1 pos2 -- fwd1
-a '1' -b -- 'pos1' 'pos2' 'fwd1'
What's the best way to delimit my positional-arguments from the forwarding ones?
Stewart
(15631 rep)
May 28, 2024, 03:40 PM
• Last activity: May 28, 2024, 04:36 PM
3
votes
1
answers
589
views
tcsh: Handle spaces in arguments when passing on to another command
I wrote a script that needs to call a command and pass on arguments. My script has its own parameters but some need to be passed through. This fails when arguments to my script have spaces in them. Here is the script, reduced to the passing on of arguments: #!/bin/tcsh set passthrough = "" checkpara...
I wrote a script that needs to call a command and pass on arguments. My script has its own parameters but some need to be passed through. This fails when arguments to my script have spaces in them.
Here is the script, reduced to the passing on of arguments:
#!/bin/tcsh
set passthrough = ""
checkparams:
if ( $# > 0 ) then
# Add the argument to passthrough, ensuring spaces are preserved
set passthrough = "$passthrough '${1:q}'"
# Show what has been added in one go
echo "Added passthrough: '${1:q}'"
shift
goto checkparams
endif
# Using echo here instead of the real command
echo $passthrough
Calling this script shows the problem:
user@host:/home/user/bin
-> ./test_preserve_passthrough a "b b" c
Added passthrough: 'a'
Added passthrough: 'b b'
Added passthrough: 'c'
'a' 'b b' 'c'
As you can see, the 4 spaces between the 'b's disappear. In fact, when I pass a single argument with spaces in it, echo receives not one argument but many as the single string will be broken up by its spaces " ". I tried many ways of quoting (single, double,
{$x:q}
) and combinations but still cannot preserve the spaces in any way.
When an argument is given to my script like a (TAB-completed) filename this\ \ is\ a\ file\ with\ spaces\ in\ its\ name
the backslashes need to be removed, and in the above example with a "b b" c
three arguments need to be passed on unchanged: a
and b b
and c
.
Ned64
(9256 rep)
May 19, 2024, 04:42 PM
• Last activity: May 20, 2024, 10:26 AM
2
votes
2
answers
197
views
Determining name of the variable passed to function
If I pass variable as a positional argument to a function, is it possible to determine the name of the variable used from inside the function, or I can only access its value? I have a function `envir-export` that I can use to define an environment variable and store it in a special environment file...
If I pass variable as a positional argument to a function, is it possible to determine the name of the variable used from inside the function, or I can only access its value?
I have a function
envir-export
that I can use to define an environment variable and store it in a special environment file that would then get sourced.
envir-export ()
{
nm="$1"
vl="$2"
envirs_trkrc="${HOME}/Opstk/envirs"
echo "export ${nm}=${vl}" >> ${envirs_trkrc}/envirs.rc
source ${envirs_trkrc}/envirs.rc
echo "$nm exported with value $vl"
}
Currently I am using by the following call
envir-export VERBOS 8
Using the name VERBOS
with value 8
.
I would like to improve on this function, both in convenience, and also functionally.
For instance, if no value is supplied then I only export the name with a value being assigned.
Vera
(1363 rep)
Sep 21, 2022, 03:38 AM
• Last activity: May 14, 2024, 08:58 AM
0
votes
2
answers
144
views
Is it possible to use a command with an argument to trigger a bash alias?
I have a program that tries to trigger a screenlock using the following commands: ``` xdg-screensaver lock xscreensaver -lock cinnamon-screensaver-command --lock ``` The problem is that I'm using Arch and I'm not using any of the screenlock programs listed above. I need one of the above commands to...
I have a program that tries to trigger a screenlock using the following commands:
xdg-screensaver lock
xscreensaver -lock
cinnamon-screensaver-command --lock
The problem is that I'm using Arch and I'm not using any of the screenlock programs listed above. I need one of the above commands to trigger my swaylock script.
Is it possible to use a command with an argument to trigger a bash alias? For example:xscreensaver -lock="cd ~/.config/hypr/scripts && ./lockscreen"
There are a lot of posts about using functions to pass arguments, but I haven't been able to find any info on how to use an argument in the command that triggers the alias. I'm guessing this isn't possible, but maybe someone has some alternative suggestions to get the same effect.
guttermonk
(113 rep)
May 5, 2024, 04:18 PM
• Last activity: May 6, 2024, 04:43 PM
Showing page 1 of 20 total questions