Reputation: 138
I'm working on converting some batch scripts into a bash script to build a project on Linux and I need to convert %%~nxD
to Bash. It is used in the following form:
FOR %%D IN ("%SOURCE_DIR%\..\..") DO SET "ProjName=%%~nxD"
If anyone could shed some light on this it would be much appreciated.
Upvotes: 1
Views: 1342
Reputation: 17420
FOR %%D IN ("%SOURCE_DIR%\..\..") DO SET "ProjName=%%~nxD"
(Assuming that is to find the third path component of the SOURCE_DIR
variable.)
In bash, that might look like this:
ProjName=$(basename `(cd $SOURCE_DIR/../..; pwd)`)
(cd
- change into the directory, pwd
- print the current directory, basename
- take the last component of the name.)
Alternatively:
ProjName=$(basename $(dirname $(dirname $SOURCE_DIR)))
(Strip two path components with the dirname
, then take the last component with the basename
.)
or, without extra commands (fast, but ugly):
TEMP1=${SOURCE_DIR%/*/*}
ProjName=${TEMP1##*/}
(The same as previous, but using the bash' built-in string expansion. Search man bash
for ##
- it would lead you directly to the string expansion description.)
The major differences between the options are:
pwd
can be used to resolve the symlinks. (Also allows for error checking.)../..
with nested dirname
calls.$SOURCE_DIR
ends with a redundant /
, it might not work as expected.Upvotes: 3
Reputation: 1943
Guessing since you didn't add what it does in DOS that you want the parent directory?
var=${PWD%*/}
if it's the current directory, no path
var=${PWD##/*}
Upvotes: 0