pure-bash-bible/manuscript/chapter5.txt

77 lines
1.1 KiB
Plaintext
Raw Permalink Normal View History

2018-06-20 08:00:33 +02:00
# FILE PATHS
2018-06-20 05:03:53 +02:00
## Get the directory name of a file path
Alternative to the `dirname` command.
**Example Function:**
```sh
dirname() {
# Usage: dirname "path"
2019-09-22 13:25:57 +02:00
local tmp=${1:-.}
2019-09-19 17:46:06 +02:00
2019-09-22 13:25:57 +02:00
[[ $tmp != *[!/]* ]] && {
printf '/\n'
return
}
2019-09-19 17:46:06 +02:00
2019-09-22 13:25:57 +02:00
tmp=${tmp%%"${tmp##*[!/]}"}
2019-09-19 15:23:20 +02:00
2019-09-22 13:25:57 +02:00
[[ $tmp != */* ]] && {
printf '.\n'
return
}
tmp=${tmp%/*}
tmp=${tmp%%"${tmp##*[!/]}"}
printf '%s\n' "${tmp:-/}"
2018-06-20 05:03:53 +02:00
}
```
**Example Usage:**
```shell
2018-06-20 05:03:53 +02:00
$ dirname ~/Pictures/Wallpapers/1.jpg
2019-09-19 15:23:20 +02:00
/home/black/Pictures/Wallpapers
2018-06-20 05:03:53 +02:00
$ dirname ~/Pictures/Downloads/
2019-09-19 15:23:20 +02:00
/home/black/Pictures
2018-06-20 05:03:53 +02:00
```
2018-06-20 05:03:53 +02:00
## Get the base-name of a file path
Alternative to the `basename` command.
**Example Function:**
```sh
basename() {
2019-09-19 19:13:44 +02:00
# Usage: basename "path" ["suffix"]
2019-09-19 20:00:15 +02:00
local tmp
2019-09-19 18:58:29 +02:00
2019-09-20 11:18:39 +02:00
tmp=${1%"${1##*[!/]}"}
2019-09-19 20:00:15 +02:00
tmp=${tmp##*/}
2019-09-20 11:17:12 +02:00
tmp=${tmp%"${2/"$tmp"}"}
2019-09-19 20:00:15 +02:00
printf '%s\n' "${tmp:-/}"
2018-06-20 05:03:53 +02:00
}
```
**Example Usage:**
```shell
$ basename ~/Pictures/Wallpapers/1.jpg
1.jpg
2019-09-19 18:58:29 +02:00
$ basename ~/Pictures/Wallpapers/1.jpg .jpg
1
2018-06-20 05:03:53 +02:00
$ basename ~/Pictures/Downloads/
Downloads
```
<!-- CHAPTER END -->