Intro To 'basename' Command In Linux
2023-05-17 - By Robert Elder
I use the 'basename' command to remove leading path components from a file or directory name. For example, when I run the 'basename' command on this file path:
basename /home/robert/important/cat.png
it will print only the file name with the directory part stripped away:
cat.png
The 'basename' command is commonly used together with the 'dirname' command as a method of parsing file paths in a shell script. Here, I have an script example script that's used to resize images:
#!/bin/bash
IMAGE_PATH=${1}
IMAGE_FILENAME=$(basename "${IMAGE_PATH}")
IMAGE_DIRNAME=$(dirname "${IMAGE_PATH}")
NEW_IMAGE_PATH="${IMAGE_DIRNAME}/resized-${IMAGE_FILENAME}"
echo "Resizing image at '${IMAGE_PATH}' to '${NEW_IMAGE_PATH}'."
convert -resize 50% "${IMAGE_PATH}" "${NEW_IMAGE_PATH}"
This script takes a single argument that's expected to be any relative or absolute path to an image file that will be resized. This script first uses the 'basename' command to isolate the name of the image file so that a prefix can be added to the resized image. The resized image file is then stored alongside the original.
Let's try running this script with a few different paths:
./do-resize.sh /home/robert/important/foo/dog.png
Resizing image at '/home/robert/important/foo/dog.png' to '/home/robert/important/foo/resized-dog.png'.
./do-resize.sh /home/robert/important/cat.png
Resizing image at '/home/robert/important/cat.png' to '/home/robert/important/resized-cat.png'.
./do-resize.sh ./cat.png
Resizing image at './cat.png' to './resized-cat.png'.
./do-resize.sh ./foo/dog.png
Resizing image at './foo/dog.png' to './foo/resized-dog.png'.
Here, you can see the original and resulting resized images:
find . -name '*.png' -exec ls -l {} \;
-rw-rw-r-- 1 robert robert 2619564 May 14 13:53 ./resized-cat.png
-rw-rw-r-- 1 robert robert 9418937 May 6 14:18 ./foo/dog.png
-rw-rw-r-- 1 robert robert 2619564 May 14 13:53 ./foo/resized-dog.png
-rw-rw-r-- 1 robert robert 9418937 May 6 14:18 ./cat.png
The 'basename' command is the most based command in the entire Linux operating system.
And that's why the 'basename' command is my favourite Linux command.
Intro To 'stty' Command In Linux
Published 2023-10-04 |
$1.00 CAD |
Intro To 'nproc' Command In Linux
Published 2023-07-15 |
Intro To 'comm' Command In Linux
Published 2023-09-06 |
How To Force The 'true' Command To Return 'false'
Published 2023-07-09 |
A Surprisingly Common Mistake Involving Wildcards & The Find Command
Published 2020-01-21 |
A Guide to Recording 660FPS Video On A $6 Raspberry Pi Camera
Published 2019-08-01 |
Intro To 'chroot' Command In Linux
Published 2023-06-23 |
Join My Mailing List Privacy Policy |
Why Bother Subscribing?
|