New in Linux bash script.
Here I tried to create some files with getopts
. For example I'd like to create 3 files called xyzfile, in command line ./createfiles -n xyzfile 3
should be given (2 arguments after the option -n
). The result should be 3 files with the names xyzfile_1, xyzfile_2 and xyzfile_3.
I tried to put my createfile()
function outside the while-loop and as well as inside the while-loop. But the option -n
doesn't work.
I also tried to create another function called foo()
with included the function createfile()
, but still something wrong there.
I have no idea anymore what I can do. Hope I can get some advices from you guys. Thank you very much!
#!/bin/bash
while getopts :n:bc opt; do
case $opt in
n) echo test 3333333
createfile() {
echo "$OPTARG"
sum=$2
for((i=1;i<=sum;i++))
do
touch "$OPTARG_${i}"
done
}
createfile $OPTARG ${2};;
b) echo "test 1111111";;
c) echo "test 2222222";;
*) echo error!;;
esac
done
Use a separate option for the count, and create your files after the option processing.
Something like:
while getopts "n:c:" opt; do
case $opt in
n) name="$OPTARG";;
c) count=$OPTARG;;
# other options...
esac
done
shift $((OPTIND -1))
while (( count > 0 )); do
touch "${name}_$count"
(( count-- ))
# ...
done