0

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

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

John, thanks so much for the help. Just another question; I thought that the "fi" ended the script, so why doe i have to put the : before the "fi". I guess im not sure why i need to create a null statement before the "fi".
@JamesCook The : stands in for the missing date command. : is a command which does nothing. You need to have a command after a then, you can't have then followed immediately by fi; it's a syntactical requirement.
The bottom script is so much easier! thank you so much for your help John.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.