Change your bash script to:
while getopts "123456" flag
do
sort -t: -k $flag "${2}"
done
Getting parameters you can use "${2}" for the second parameter
Frage
This is my bash script that sorts a file by columns.
while getopts "123456" flag
do
sort -t: -k $flag names.txt
done
Right now it does exactly what I need, but I need to have the filename be a parameter too.
The input right now is ./sortScrpt -2.
I need the input to look like ./sortScript -2 names.txt
Any help would be great. Thanks
Lösung
Change your bash script to:
while getopts "123456" flag
do
sort -t: -k $flag "${2}"
done
Getting parameters you can use "${2}" for the second parameter
Andere Tipps
Something to get you started:
#!/bin/bash
while getopts ":2:" opt; do
case $opt in
2)
echo "-2 was triggered, Parameter: $OPTARG" >&2
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
output:
$ ./a.sh -2 names.txt
-2 was triggered, Parameter: names.txt
If you want multiple sort parameters then you can update your script as:
#first parse -f fname
getopts "f:" f
fname=$OPTARG
while getopts "123456" flag
do
sort -t: -k $flag $fname
done
You can run this script as
$ ./script.sh -f names.txt -2
or for multiple sorts
$ ./script.sh -f names.txt -2 -3
EDIT revised for "sort-arg then file" requirement + error checking:
#!/bin/bash
sflag=""
sfile=""
while getopts "123456" flag
do
[ -z "$sflag" ] && sflag="$flag"
done
shift $(($OPTIND - 1))
sfile="$1"
if [[ "$sflag" ]] && [[ "$sfile" ]];
then
sort -t: -k $sflag $sfile
else
# error - bail out
echo "usage: $0 -[123456] file.txt" >&2
exit 1
fi
OPTIND is set by getopts and will either point to $#+1 (e.g. no extra parameters) or to the first parameter not matching your getopts-flags.