James Cook
James Cook

Reputation: 1

Bash scripting arguments

I am currently taking a linux class. I pretty much have to learn stuff on my own. I have writtent this script to produce a date format based on the argument. Ie (./script.sh one). I am having an issue getting this script to do just that. I think that i have something wrong. Any help would be greatly appreciated. here is the script:

#!/bin/bash


if [ $1="one" ]
    then
        date +%m-%d-%y 

elif [ $2="two" ]
    then
        date +%d-%m-%y

elif [ $3="three" ]
    then
        date +%A,%B-%d,%Y 

elif [ $4="four" ]
    then
        date +%s 
elif [ $5="five" ]
    then

fi

Upvotes: 0

Views: 125

Answers (1)

John Kugelman
John Kugelman

Reputation: 362087

Shell scripts are counter-intuitively whitespace-sensitive. There must be spaces before and after the equal signs. You also can't have a completely empty if statement. There must be at least one statement in there. If you don't have anything, writing : is the common idiom for a null statement.

if [ $1 = "one" ]; then
    date +%m-%d-%y 
elif [ $2 = "two" ]; then
    date +%d-%m-%y
elif [ $3 = "three" ]; then
    date +%A,%B-%d,%Y 
elif [ $4 = "four" ]; then
    date +%s 
elif [ $5 = "five" ]; then
    :
fi

I am guessing you might also want to use $1 in all of the checks, not $1 through $5—i.e., check what the first argument is. If that's true then you could swap the ifs for a case.

case $1 in
    one)   date +%m-%d-%y;;
    two)   date +%d-%m-%y;;
    three) date +%A,%B-%d,%Y;;
    four)  date +%s;;
    five)  ;;
esac

Upvotes: 3

Related Questions