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
  • 884
  • 2
  • 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
  • 497,756
  • 71
  • 530
  • 681
SLePort
  • 15,211
  • 3
  • 34
  • 44
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
  • 24,009
  • 2
  • 33
  • 57
  • 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
  • 133,037
  • 18
  • 149
  • 215
Dinesh
  • 16,014
  • 23
  • 80
  • 122