Question

Given this variable in tcsh:

set i = ~/foo/bar.c

how can I get just the directory part of $i?

~/foo
Was it helpful?

Solution

If your system provides a 'dirname' command you could:

set i = `dirname ~/foo/bar.c`
echo $i

Note the missing $ in front of the variable name. This solution is shell agnostic though.

OTHER TIPS

The way I found to do it while waiting for answers here:

set i = ~/foo/bar.c
echo $i:h

result:

~/foo

For completely, getting the file name is accomplished with the basename command:

set j = `basename ~/foo/bar.c`
echo $j

Here is something different from above:
Available in tcsh but few other shells AFAIK

> set i = ~/foo/bar.c
> echo ${i:t}
bar.c
> echo ${i:h}
/home/erflungued/foo
echo $i | awk -F"/" '{$NF="";print}' OFS="/"

Use dirname command, for example:

set i = `dirname "~/foo/bar.c"`

Notice the quotation marks around path. It's important to include them. If you skip the quotation marks, dirname will fail for paths which contain spaces. Mind that ~/ expression evaluates before dirname is executed, thus even such simple example may fail if quotation marks are not used and home path includes spaces.

Of course the same problem applies also to all other commands, it's good practice to always surround argument to a command with quotation marks.

Use dirname "$i" indeed, and not ${i:h}.

The latter does not produce the intended result if $i contains only a file name (no path), while dirname correctly returns the current directory . in that case.

> set i = bar.c
> echo ${i:h}
bar.c
> dirname "$i"
.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top