Reputation: 215
For example, I have a bash script named getimage
. In the script I have:
wget http://www.example.com/images/1.jpg
If I type bash getimage
in the terminal, it would download the picture.
But what I want is to type bash getimage 2
or bash getimage 3
and so on in the terminal and download 2.jpg
or 3.jpg
respectively.
Basically, I want to type a number in terminal (bash getimage number
) and have it correspond to wget http://www.example.com/images/number.jpg
.
Upvotes: 3
Views: 3512
Reputation: 1283
A minimal script for what you want would be the following.
#!/usr/bin/env bash
wget "http://www.example.com/images/${1}.jpg"
The first line is called a shebang The shebang tells the script which program to run it in. In this case we use the env program to find the default version of bash in the current environment.
On the second line we simply run your wget
command, but we pass in the variable $1
. This is a special variable called a positional parameter, in this case the first argument passed to the script.
To run the command, make it executable with chmod +x getimage
and then call it like so:
./getimage 1
./getimage 2
etc.
Upvotes: 2
Reputation: 24812
Here's what I would do :
#!/bin/bash
image_name=${1-1}
wget "http://www.example.com/images/$image_name.jpg"
The script is to be called as getimage x
. If x
is omitted, 1
will be chosen as a default value.
The first line is a shebang : it tells your shell to execute the script with the specified executable, /bin/bash
.
The second line defines an image_name
variable and assigns it the result of an expression. That expression is a parameter expansion, which will return $1
(that is the first parameter passed to the script) if it is defined, or 1
either. It's hard to see in this case, but the syntax is ${variable-default}
where variable
is a variable name whose value you want, and default
a default used when that variable isn't defined.
The third line is your command, where the static 1
has been replaced by a reference to the image_name
variable. Note that ""
have been added in case the image_name
contains spaces : that would break the url in two parts that would be understood by wget
as two separate parameters. Don't use ''
though, the $variable
contained in the string wouldn't be expanded to their value.
Upvotes: 2
Reputation: 1770
As Aaron mentioned in comments, you need to give the variables externally by specifying them as $1
or $2
etc in your script.
The way to do this is-
wget http://www.example.com/images/"$1".jpg
Then launch your script as bash getimage 1
If (as I suspect) you want to wget
in a loop, do-
for i in {1..10} ; do bash getimage "$i" ; done
Or from the commandline,
for i in {1..10} ; do wget http://www.example.com/images/"$i".jpg ; done
Upvotes: 2