Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script argument present or not

Tags:

linux

shell

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

like image 999
AabinGunz Avatar asked Sep 06 '25 10:09

AabinGunz


2 Answers

if [ -z "$1" ]; then
    echo "usage: $0 directory"
    exit
fi
like image 196
matcheek Avatar answered Sep 09 '25 07:09

matcheek


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

like image 23
bash-o-logist Avatar answered Sep 09 '25 07:09

bash-o-logist