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!

Chris
  • 824
  • 1
  • 11
  • 22

3 Answers3

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.

chepner
  • 446,329
  • 63
  • 468
  • 610
SLePort
  • 14,775
  • 3
  • 30
  • 41
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.

Aaron
  • 23,167
  • 2
  • 30
  • 53
  • 1
    This works, but isn't recommended due to the highly inefficient use of multiple external programs. – chepner Mar 15 '16 at 15:00
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.

Donal Fellows
  • 126,337
  • 18
  • 137
  • 204
Dinesh
  • 15,524
  • 23
  • 76
  • 118