I am using the getopts built-in function to parse arguments to my bash script. I then take the values assigned to each flag and use in a subsequent command.
Part of myscript.sh:
while getopts "s:n:e" opt; do
case $opt in
n) name=$OPTARG;;
e) area=$OPTARG;;
s) part+=("$OPTARG");;
esac
done
shift $((OPTIND -1))
getArray(){ for val in "${part[@]}"; do
echo "$val"
done }
getPart(){ getArray | while read -r param1; do
echo "$param1" | sed 's/=.*//'}
done }
parts=$(getPart)
I have a info.csv
config file:
name,part,area,partcode
fiat,exhaust,store,123
fiat,engine,store,132
ford,exhaust,store,145
ford,windscreen,store,134
Once the command is run I use grep "$name,$part,$area" info.csv | cut -d, f4
to extract a specific field based on what the user inputs as the values of their flags when the script is run.
I use the -s
flag either once, twice or three times with different values each time I run the script.
The values come in the wrong format (i.e. -s fiat=1 -s exhaust=2
and the column I am using them to access in the grep
statement above requires them to be in this format fiat
and exhaust
) so I use sed
to remove the =1
and =2
.
I want to reuse these now correctly formatted values as my $part
variable. But I am having trouble reassigning the newly formatted values back to the $part
variable.
My question would be:
- How do you reassign variables in bash after performing a command on them to get them in the correct format?