bashdirname

bash: unable to trim path with "dirname" - path is a directory


According to dirname --help, command dirname /usr/bin/sort will output /usr/bin

So I tried this:

  1 #!/bin/bash
  2
  3 rawPath="${1}"
  4 trimmed=dirname $rawPath
  5 echo $trimmed

And ran the script:

 bash ./trimPath.sh /files/data/swx_i/raw/2020/03

Output:

./trimPath.sh: line 5: /files/data/swx_i/raw/2020/03: is a directory

Is it because I store the path in the variable or something else?

GNU bash, version 4.1.2(2)-release (x86_64-redhat-linux-gnu)


Solution

  • This line:

    trimmed=dirname $rawPath
    

    will temporarily set the trimmed environment variable to be dirname and then try to run $rawPath. That's what it's complaining about, the fact that you're trying to run the directory.

    If you want the output of that command placed in a variable, you're looking at something like:

    trimmed="$(dirname "$rawPath")"