Unix & Linux Asked by Atlantic on December 3, 2021
I have a script called test_script that needs to run a file called run_command as follows:
./run_command <input path>
If I supply the script with the following arguments:
./test_script argument1=sometext argument2=othertext inputpath=/folder1/folder2/file.txt argument4=moretext
How can I make the script find the argument inputpath=/folder1/folder2/file.txt and pass /folder1/folder2/file.txt to run_command? Keep in mind that inputpath=/folder1/folder2/file.txt won’t necessarily always be in third place and the amount of arguments supplied may vary.
With zsh
:
#! /bin/zsh -
inputpath=(${${(M)argv:#inputpath=*}#*=})
(($#inputpath > 0)) && ./run-command $inputpath
Would extract all the paths in inputpath=path
arguments to the script and store the non-empty ones in the $inputpath
array. Then we run ./run-command
with those inputpath as arguments if any were found.
POSIXly, you could do something like:
#! /bin/sh -
run_with_extracted_keyword() (
cmd="${1?}" keyword="${2?}"
shift 2
for arg do
case $arg in
("$keyword="*) set -- "$@" "${arg#*=}"
esac
shift
done
[ "$#" -gt 0 ] && exec "$cmd" "$@"
)
run_with_extracted_keyword ./run-command inputpath "$@"
GNUly, you could do:
#! /bin/bash -
set -o pipefail
printf '%s ' "$@" |
LC_ALL=C grep -zPo '^inputpath=K(?s:.*)' |
xargs -r0 ./run-command
Answered by Stéphane Chazelas on December 3, 2021
What I would do, if you control the input, and can restrict the script access to prevent shell injection as stated by Stéphane in comments:
#!/bin/bash
for arg; do
declare "$arg"
done
echo "$argument1"
sometext
Usually, to access positional parameters, you can do echo $1
, $2
, $3
...
But if you use this var=value
form, this code will fit better
Answered by Gilles Quenot on December 3, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP