Pretty self explanatory.
The first argument should be:
- Checked if the file exists
- Echo that file's absolute path
For example:
+akiva@akiva-ThinkPad-X230:~$ ./myscript myfile.txt
/home/akiva/myfile.txt
Thanks
Pretty self explanatory.
The first argument should be:
For example:
+akiva@akiva-ThinkPad-X230:~$ ./myscript myfile.txt
/home/akiva/myfile.txt
Thanks
Script is not necessary. A single readlink
command is sufficient:
$ cd /etc/
$ readlink -e passwd
/etc/passwd
From the man readlink
:
-e, --canonicalize-existing
canonicalize by following every symlink in every component
of the given name recursively, all components must exist
If your script is
#!/bin/bash
[[ -e "$1" ]] && readlink -f -- "$1"
And has execute permission (chmod u+x scriptname
) You can enter
./scriptname file
To get the full path if the file exists (although Serg is right that the test is redundant if we use readlink -e
and George is right to use realpath
rather than readlink
)
[[ -e "$1" ]]
test whether $1
, the first argument to the script, exists&&
if it does (if the previous command was successful) then do the next commandreadlink -f -- "$1"
print the full path (to the real file, even if $1
is a symlink)OP requested special characters be printed with escapes. There must be a smart way* but I did it like this (although it won't deal with single quotes - but those cannot be escaped anyway)
[[ -e "$1" ]] && readlink -f -- "$1" | sed -r 's/\||\[|\]| |!|"|\$|%|\^|&|\*|\(|\)\{|\}|\#|@|\;|\?|<|>/\\&/g'
If it's only spaces you're worried about, you could make that
sed 's/ /\\ /g'
This would get single quotes (not very usefully) and spaces
sed -r "s/'| /\\\&/g"
But I don't think you can catch both single quotes and double quotes...
* Here's the smart way, 100% credit to steeldriver
[[ -e "$1" ]] && printf "%q\n" "$(readlink -f -- "$1")"
printf '%q'
is the "smart way"? e.g. printf "%q\n" "$(readlink -f -- "$1")"
– steeldriver
Mar 14 '17 at 18:11
#!/bin/bash
[[ -e "$1" ]] && echo realpath -e "$1"
Update to take care of non-alphanumeric characters:
#!/bin/bash
[[ -e "$1" ]] && echo "$1" | sed -r 's/[^a-zA-Z0-9\-]/\//g' | realpath -e "$1"
Prepare script: chmod +x script_name
, then
use it : ./script_name filename
Information:
[[ -e "$1" ]]
: check if the passed file exists.readlink
command. My shell, mksh
for instance, has that as built-in, so syntax is different. Please note that in your answer.
– Sergiy Kolodyazhnyy
Mar 14 '17 at 17:27
realpath
which is what you're using in your answer, is a builtin command of some shells. Not readlink
which isn't builtin and is instead a standard POSIX-defined tool. That means that the behavior of realpath
can vary depending on the shell used.
– terdon
Mar 14 '17 at 17:42
dash
and bash
are the only shells present in default Ubuntu. It's just a caution, which should be mentioned
– Sergiy Kolodyazhnyy
Mar 14 '17 at 17:43
sed 's# #\ #g'
– terdon Mar 14 '17 at 17:44