2

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}

  • 3
    You're likely to shoot yourself in the foot going this way, this sounds like a XY problem, what is the problem you're trying to solve by using this ? – Tensibai Apr 24 '18 at 14:07
  • Have you tried just using them? – cunninghamp3 Apr 24 '18 at 14:07
  • @Tensibai none really, just instead of doing variable substitution, I would like to take advantage of them – user1371264 Apr 24 '18 at 14:18
  • @cunninghamp3 no to be honest, but I know that history is disabled by default in scripts and I could not think of way to use the modifiers in variable expansion. – user1371264 Apr 24 '18 at 14:20
2

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 /.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.