How can I put the directory (not full path) of the file which opened the script into a variable? I assume this is the same as $1, so I would like file’s path to yield the same result when executed from terminal.
Explained;
#!/bin/bash
script.sh '~/foo/bar/file.ext'
#I want to put "bar" into a variable.
It should also work when “file.ext” opens with “script.sh” through GUI.
You should checkout both the dirname and basename programs, The
dirnameprogram takes an argument and removes the name of the program from the rest of the path. That is, it will give you the directory name.The
basenameprogram does the opposite. Given the name of a path, it will remove all directories and just leave the file name:Now, the rest depends upon the shell. In BASH (which is the default shell on Linux and what you’ve tagged, you can use the $(command) syntax. This takes the output of the command and replaces it on the command line. For example:
In the above example, the
dirnamecommand took the name of the directory, replaced everything in the$()syntax and allowed me to set the name of my variablemydirectory.You can use them in combination to get what you want:
You can also combine the
basenameanddirnamecommands together:When a shell program executes, it puts each and every parameter on the command line into a count variable. For example:
Inside of the program
myprog, the following variables are set:One more thing with the BASH shell: There’s a special filter syntax to parse variables.
${variable#pattern}– Left small pattern. Removes the smallest pattern from the left side of the variable${variable##pattern}– Left large pattern. Removes the largest pattern from the left side of the variable${variable%pattern}– Right small pattern. Removes the smallest pattern from the right side of the variable${variable%%pattern}– Right large pattern. Removes the largest possible pattern from the right side of the variableHere’s an example:
In the above cases, the pattern was
*|. This means any combination of letters followed by a|In the first one, the smallest match wasONE|. In the second one, it wasONE|TWO|THREE|. You can also use this to simulate thebasenameanddirnamecommands: