2

I have a bash file:

agro_233_720

Inside this bash script I would like to use as variables the part's of it's name that underscore delimitates:

name= agro
ip= 233
resolution= 720

How can I get them ?

I tried to write:

name=`basename "$0"`

but it outputs the hole name (agro_233_720)

Thank you!

0

3 Answers 3

3

With read :

$ IFS='_' read name ip resolution <<< "agro_233_720"
$ printf 'name: %s\nip: %s\nresolution: %s\n' "$name" "$ip" "$resolution"
name: agro                                                                                                                                                                                                                                   
ip: 233                                                                                                                                                                                                                                      
resolution: 720 

It splits the string on the IFS delimiter and assign values to vars.

Sign up to request clarification or add additional context in comments.

Comments

2
name=$(basename $0 | cut -d_ -f1)
ip=$(basename $0 | cut -d_ -f2)
resolution=$(basename $0 | cut -d_ -f3)

cut splits its input around the delimiter provided with -d and returns the field at the index specified by -f.

See SLePort's answer for a more efficient solution extracting the 3 variables at once without the use of external programs.

1 Comment

This works, but isn't recommended due to the highly inefficient use of multiple external programs.
2

With Tcl it can be written as follows,

lassign [ split $argv0 _] name ip resolution

If your Tcl's version is less than 8.5, then use lindex to extract the information.

set input [split $argv0 _]
set name [lindex $input 0]
set ip [lindex $input 1]
set resolution [lindex $input 2]

The variable argv0 will have the script name in it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.