It would be handy if I could use bash history modifiers in scripts such as:
!$:h
to get the path of a file.
Is there a way to use them in scripts? Eg ${1:h}
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityIt would be handy if I could use bash history modifiers in scripts such as:
!$:h
to get the path of a file.
Is there a way to use them in scripts? Eg ${1:h}
Those history modifiers could also be applied to variables in csh
where the feature comes from.
But bash
chose not to copy that part. zsh
did though. So you could use zsh
instead of bash
here:
$ file=foo/bar/
$ echo $file:h # (or ${file:h})
foo
(the example chosen to show that zsh
actually improved upon csh
which would have returned foo/bar
instead; it also supports quite a few additional useful modifiers).
In other shells, you can always use dirname
instead:
$ dir=$(dirname -- "$file")
$ echo "$dir"
foo
(though beware it doesn't work correctly for directory names that end in newline characters).
In bash
, like in other POSIX shells, you can use ${file%/*}
but it gives unexpected results in a few corner cases like that foo/bar/
or foo
or /
.