7

If I have a string such as

/home/user/a/directory/myapp.app 

or just

/home/user/myapp.app 

how can I split this so that I just have two variables (the path and the application)

e.g.

path="/home/user/"
appl="myapp.app"

I've seen numerous examples of splitting strings, but how can I get just the last part, and combine all the rest?

IGGt
  • 2,457

2 Answers2

13

The commands basename and dirname can be used for that, for example:

$ basename /home/user/a/directory/myapp.app 
myapp.app
$ dirname /home/user/a/directory/myapp.app 
/home/user/a/directory

For more information, do not hesitate to do man basename and man dirname.

perror
  • 3,239
  • 7
  • 33
  • 45
6

With any POSIX shell:

$ str=/home/user/a/directory/myapp.app
$ path=${str%/*}
$ app=${str##*/}
$ printf 'path is: %s\n' "$path"
path is: /home/user/a/directory
$ printf 'app is: %s\n' "$app"
app is: myapp.app

save you for two processes forking.

In case of /myapp.app, myapp.app and /path/to/myapp.app, basename/dirname are more graceful. See also this question for more discussion.

cuonglm
  • 153,898