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
  • 784
  • 10
  • 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
  • 389,128
  • 51
  • 403
  • 529
SLePort
  • 14,405
  • 3
  • 28
  • 39
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
  • 21,986
  • 2
  • 27
  • 48
  • 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
  • 120,022
  • 18
  • 134
  • 199
Dinesh
  • 14,859
  • 20
  • 72
  • 113