简体   繁体   中英

Shell script argument present or not

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

if [ -z "$1" ]; then
    echo "usage: $0 directory"
    exit
fi

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

If you want to use named args, check out getopts . It's made for extracting args by name. That link also has examples of how to use it.

#!/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

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 ie, 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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM