Can I feed a bash script a local file into $1 and have it echo the file's absolute path? [duplicate]
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
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
)
Notes
-
[[ -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 command -
readlink -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")"
#!/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.