Reputation: 12347
I have a shell script, where sometimes user gives the required arg sometimes they forget. So I needed someway in which if the user has already provided the particular argument then the user should not be prompted for that particular arg. Can anyone help?
Example script:
#!/bin/sh
if [ $GAME =="" ]
then
echo Enter path to GAME:
read GAME
else
echo $GAME
fi
Example O/P 1:
$ ./sd.sh -GAME asdasd
Enter path to GAME:
?asd
Example O/P 2:
$ ./sd.sh
Enter path to GAME:
asd
Upvotes: 4
Views: 12061
Reputation: 12347
Here is my version of shell script without using getopts that solves the problem. The problem that i am facing with getopts is to give named arguments as -GAME instead only -g works i.e., single character.
Note: Here -user and -pass args are for java so i don't need sh script to ask it, as java does the job if they are not already provided.
#!/bin/sh game=0 if [ $# -ge 1 ];then if [ ${6} = "-GAME" ];then game=1 fi if [ $game -ne 1 ];then echo "Enter path to GAME location" read GAME else GAME=${7} fi echo "Game:" $1 ", Game location: " $GAME else echo "usage: ./run.sh gamename" echo "usage: ./run.sh gamename [-user] [username] [-pass] [password] [-GAME] [path]" fi
Output 1:
./run.sh COD4 -user abhishek -pass hereiam -GAME /home/games
Game: COD4, Game location: /home/games
Output 2:
./run.sh COD4
./run.sh: line 4: [: =: unary operator expected
Enter path to GAME location
/home/mygames
Game: COD4, Game location: /home/mygames
Thanks everyone for their efforts :)
Upvotes: 0
Reputation: 6911
you can check for first argument using $#
if [ $# -ne 1 ];then
read -p "Enter game" GAME
else
GAME="$1"
fi
$#
means number of arguments. This scripts checks whether number of arguments is 1. If you want to check fifth argument, then use $5
. If you really want something more reliable, you can choose to use getopts
. Or the GNU getopt which supports long options
Upvotes: 5
Reputation: 246744
#!/bin/sh
game=""
usage="usage: $0 -g game"
while getopts ":hg:" option; do
case "$option" in
h) echo "$usage"
exit
;;
g) game="$OPTARG"
;;
?) echo "illegal option: $OPTARG" >&2
echo "$usage" >&2
exit 1
;;
esac
done
[ -z "$game" ] && read -p "enter game: " game
Upvotes: 1