Sometimes some tutorials are aimed at explaining somewhat more exotic and strange commands, on the other hand, there are some that include serial distributions and are not as popular as cd, ls, cat, etc., but they are just as practical. In this tutorial I will show you what can be done with two of those commands: basename and tell me.
Perhaps a priori they seem absurd to you and that they have no use, but they have pretty practical applications in some cases, such as, for example, in scripts where you need to extract some part of a path, such as the name of the file or the directory so that another command operates on this ...
What are they for
These commands are very basic, and its functions are:
- basename: used to extract the name of the file from a path.
- dirname: used to extract the directory name from a path.
Examples of use
Here you can see some examples how to use them:
- For example, to use basename with / etc / passwd, and that it returns the name of the file in its output, in this case passwd:
basename /etc/passwd
- You can also specify an extension so that it gives you the name of the file without the extension. For example, suppose you want to extract the name of an image /home/media/test.jpg without the jpg extension (it would return experiment):
basename -s .jpg /home/media/prueba.jpg
- You can even process multiple routes at once separately, for this you have to use the -a option:
basename -a /etc/passwd /var/log/boot.log
- To do the opposite, and give you the name of the directory, without the name of the file, then you have to use dirname. For example, if you want to use it in the path /var/spool/mail/test.txt and have it return / var / spool / mail, then use:
dirname /var/spool/mail/prueba.txt
As for a utility in a script, here you have another example. Imagine that you have a simple script, and that in it there is a path that is variable. But you want it to show the directory that contains a file, regardless of the file, in that case you could have something like:
pathname="/home/usuario/data/fichero" result=$(dirname "$pathname") echo $result
Obviously, in this script the "pathname" would always be the same static declared by the constant at the beginning, but there may be cases in which it is not, and that is where it becomes practical. For example: uterine
/*script para convertir una imagen gif en png*/ #!/bin/sh for file in *.gif;do #Salir si no hay ficheros if [! -f $file];then exit fi b='basename $file .gif' echo NOW $b.gif is $b.png giftopnm $b.gif | pnmtopng >$b.png done
A good example of those things that when you are learning you see useless, but when you get to the subject you see how practical they are.