1

I know how to ask questions in bash like "Would you like to create a directory" and based on that input do something. But I would like to create a bash script where I could do:

./somescriptname.sh install
./somescriptname.sh update
./somescriptname.sh assets get asset-name
./somescriptname.sh install
./somescriptname.sh update
./somescriptname.sh assets get all

I am not really sure how to read command line arguments passed in using bash.

3 Answers 3

2

Use $1, $2, etc. for accessing command-line arguments:

#!/bin/sh

echo "Arg 1: $1"
echo "Arg 2: $2"
echo "All args (as one string): $*"
echo "All args (passed to echo each as a different argument): $@"
Sign up to request clarification or add additional context in comments.

1 Comment

And quote them properly.
2

you get the args from $1,$2, $3 ... arg $0 is the script name

for example. this takes 3 args. if $3 is not present nothing is printed.

#!/bin/bash
echo "the $1 eats a $2 every time there is a $3"
echo "bye:-)"

if this is foo.sh: then on the command line just do: ./foo.sh boy spinach meal

also you should learn get ops so you can easily test the 'arguments'. since you have more than one. you may want to give each arg a definition. http://wiki.bash-hackers.org/howto/getopts_tutorial

Comments

1

From Bash Reference Manual: Positional Parameters

A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit.

Comments

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.