Check if directory mounted with bash - linux

I am using
mount -o bind /some/directory/here /foo/bar
I want to check /foo/bar though with a bash script, and see if its been mounted? If not, then call the above mount command, else do something else. How can I do this?
CentOS is the operating system.

You didn't bother to mention an O/S.
Ubuntu Linux 11.10 (and probably most up-to-date flavors of Linux) have the mountpoint command.
Here's an example on one of my servers:
$ mountpoint /oracle
/oracle is a mountpoint
$ mountpoint /bin
/bin is not a mountpoint
Actually, in your case, you should be able to use the -q option, like this:
mountpoint -q /foo/bar || mount -o bind /some/directory/here /foo/bar

Running the mount command without arguments will tell you the current mounts. From a shell script, you can check for the mount point with grep and an if-statement:
if mount | grep /mnt/md0 > /dev/null; then
echo "yay"
else
echo "nay"
fi
In my example, the if-statement is checking the exit code of grep, which indicates if there was a match. Since I don't want the output to be displayed when there is a match, I'm redirecting it to /dev/null.

The manual of mountpoint says that it:
checks whether the given directory or file is mentioned in the /proc/self/mountinfo file.
The manual of mount says that:
The listing mode is maintained for backward compatibility only. For
more robust and customizable output use findmnt(8), especially in your
scripts.
So the correct command to use is findmnt, which is itself part of the util-linux package and, according to the manual:
is able to search in /etc/fstab, /etc/mtab or /proc/self/mountinfo
So it actually searches more things than mountpoint. It also provides the convenient option:
-M, --mountpoint path
Explicitly define the mountpoint file or directory. See also --target.
In summary, to check whether a directory is mounted with bash, you can use:
if [[ $(findmnt -M "$FOLDER") ]]; then
echo "Mounted"
else
echo "Not mounted"
fi
Example:
mkdir -p /tmp/foo/{a,b}
cd /tmp/foo
sudo mount -o bind a b
touch a/file
ls b/ # should show file
rm -f b/file
ls a/ # should show nothing
[[ $(findmnt -M b) ]] && echo "Mounted"
sudo umount b
[[ $(findmnt -M b) ]] || echo "Unmounted"

My solution:
is_mount() {
path=$(readlink -f $1)
grep -q "$path" /proc/mounts
}
Example:
is_mount /path/to/var/run/mydir/ || mount --bind /var/run/mydir/ /path/to/var/run/mydir/
For Mark J. Bobak's answer, mountpoint not work if mount with bind option in different filesystem.
For Christopher Neylan's answer, it's not need to redirect grep's output to /dev/null, just use grep -q instead.
The most important, canonicalize the path by using readlink -f $mypath:
If you check path such as /path/to/dir/ end with backslash, the path in /proc/mounts or mount output is /path/to/dir
In most linux release, /var/run/ is the symlink of /run/, so if you mount bind for /var/run/mypath and check if it mounted, it will display as /run/mypath in /proc/mounts.

I like the answers that use /proc/mounts, but I don't like doing a simple grep. That can give you false positives. What you really want to know is "do any of the rows have this exact string for field number 2". So, ask that question. (in this case I'm checking /opt)
awk -v status=1 '$2 == "/opt" {status=0} END {exit status}' /proc/mounts
# and you can use it in and if like so:
if awk -v status=1 '$2 == "/opt" {status=0} END {exit status}' /proc/mounts; then
echo "yes"
else
echo "no"
fi

The answers here are too complicated just check if the mount exists using:
cat /proc/mounts | tail -n 1
This only outputs the last mounted folder, if you want to see all of them just remove the tail command.

Another clean solution is like that:
$ mount | grep /dev/sdb1 > /dev/null && echo mounted || echo unmounted
For sure, 'echo something' can be substituted by whatever you need to do for each case.

In my .bashrc, I made the following alias:
alias disk-list="sudo fdisk -l"

Related

How to check if two paths are equal in Bash?

What's the best way to check if two paths are equal in Bash? For example, given the directory structure
~/
Desktop/
Downloads/ (symlink to ~/Downloads)
Downloads/
photo.png
and assuming that the current directory is the home directory, all of the following would be equivalent:
./ and ~
~/Desktop and /home/you/Desktop
./Downloads and ~/Desktop/Downloads
./Downloads/photo.png and ~/Downloads/photo.png
Is there a native Bash way to do this?
Bash's test commands have a -ef operator for this purpose
if [[ ./ -ef ~ ]]; then ...
if [[ ~/Desktop -ef /home/you/Desktop ]]; then ...
etc...
$ help test | grep -e -ef
FILE1 -ef FILE2 True if file1 is a hard link to file2.
You can use realpath. For example:
realpath ~/file.txt
Result: /home/testing/file.txt
realpath ./file.txt
Result: /home/testing/file.txt
Also take a look at a similar answer here: bash/fish command to print absolute path to a file
Native bash way:
pwd -P returns the physical directory irrespective of symlinks.
cd "$dir1"
real1=$(pwd -P)
cd "$dir2"
real2=$(pwd -P)
# compare real1 with real2
Another way is to use cd -P, which will follow symlinks but leave you in the physical directory:
cd -P "$dir1"
real1=$(pwd)
cd -P "$dir2"
real2=$(pwd)
# compare real1 with real2
If you have coreutils 8.15 or later installed, you have a realpath command that fully normalizes a path. It removes any . and .. components, makes the path absolute, and resolves all symlinks. Thus:
if [ "$(realpath "$path1")" = "$(realpath "$path2")" ]; then
echo "Same!"
fi
Methods based on resolving symlinks fail when there are other factors involved. For example, bind mounts. (Like mount --bind /raid0/var-cache /var/cache
Using find -samefile is a good bet. That will compare filesystem and inode number.
-samefile is a GNU extension. Even on Linux, busybox find probably won't have it. GNU userspace and Linux kernel often go together, but you can have either without the other, and this question is only tagged Linux and bash.)
# params: two paths. returns true if they both refer to the same file
samepath() {
# test if find prints anything
[[ -s "$(find -L "$1" -samefile "$2")" ]] # as the last command inside the {}, its exit status is the function return value
}
e.g. on my system:
$ find /var/tmp/EXP/cache/apt/archives/bash_4.3-14ubuntu1_amd64.deb -samefile /var/cache/apt/archives/bash_4.3-14ubuntu1_amd64.deb
/var/tmp/EXP/cache/apt/archives/bash_4.3-14ubuntu1_amd64.deb
$ stat {/var/tmp/EXP,/var}/cache/apt/archives/bash_4.3-14ubuntu1_amd64.deb
File: ‘/var/tmp/EXP/cache/apt/archives/bash_4.3-14ubuntu1_amd64.deb’
...
Device: 97ch/2428d Inode: 2147747863 Links: 1
...
File: ‘/var/cache/apt/archives/bash_4.3-14ubuntu1_amd64.deb’
Device: 97ch/2428d Inode: 2147747863 Links: 1
You can use find -L for cases where you want to follow symlinks in the final path component:
$ ln -s /var/cache/apt/archives/bash_4.3-14ubuntu1_amd64.deb foo
$ find /var/cache/apt/archives/bash_4.3-14ubuntu1_amd64.deb -samefile foo
$ find -L /var/cache/apt/archives/bash_4.3-14ubuntu1_amd64.deb -samefile foo
/var/cache/apt/archives/bash_4.3-14ubuntu1_amd64.deb
Obviously this works for paths which refer to directories or any type of file, not just regular files. They all have inode numbers.
usage:
$ samepath /var/cache/apt/ /var/tmp/EXP/cache/apt/ && echo true
true
$ ln -sf /var/cache/apt foobar
$ samepath foobar /var/tmp/EXP/cache/apt/ && echo true
true
samepath /var/tmp/EXP/cache/apt/ foobar && echo true
true
samepath foobar && echo true # doesn't return true when find has an error, since the find output is empty.
find: `': No such file or directory
So find -L dereferences symlinks for -samefile, as well as for the list of paths. So either or both can be symlinks.

Linux Shell Script: How to detect NFS Mount-point (or the Server) is dead?

Generally on NFS Client, how to detect the Mounted-Point is no more available or DEAD from Server-end, by using the Bash Shell Script?
Normally i do:
if ls '/var/data' 2>&1 | grep 'Stale file handle';
then
echo "failing";
else
echo "ok";
fi
But the problem is, when especially the NFS Server is totally dead or stopped, even the, ls command, into that directory, at Client-side is hanged or died. Means, the script above is no more usable.
Is there any way to detect this again please?
"stat" command is a somewhat cleaner way:
statresult=`stat /my/mountpoint 2>&1 | grep -i "stale"`
if [ "${statresult}" != "" ]; then
#result not empty: mountpoint is stale; remove it
umount -f /my/mountpoint
fi
Additionally, you can use rpcinfo to detect whether the remote nfs share is available:
rpcinfo -t remote.system.net nfs > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo Remote NFS share available.
fi
Added 2013-07-15T14:31:18-05:00:
I looked into this further as I am also working on a script that needs to recognize stale mountpoints. Inspired by one of the replies to "Is there a good way to detect a stale NFS mount", I think the following may be the most reliable way to check for staleness of a specific mountpoint in bash:
read -t1 < <(stat -t "/my/mountpoint")
if [ $? -eq 1 ]; then
echo NFS mount stale. Removing...
umount -f -l /my/mountpoint
fi
"read -t1" construct reliably times out the subshell if stat command hangs for some reason.
Added 2013-07-17T12:03:23-05:00:
Although read -t1 < <(stat -t "/my/mountpoint") works, there doesn't seem to be a way to mute its error output when the mountpoint is stale. Adding > /dev/null 2>&1 either within the subshell, or in the end of the command line breaks it. Using a simple test: if [ -d /path/to/mountpoint ] ; then ... fi also works, and may preferable in scripts. After much testing it is what I ended up using.
Added 2013-07-19T13:51:27-05:00:
A reply to my question "How can I use read timeouts with stat?" provided additional detail about muting the output of stat (or rpcinfo) when the target is not available and the command hangs for a few minutes before it would time out on its own. While [ -d /some/mountpoint ] can be used to detect a stale mountpoint, there is no similar alternative for rpcinfo, and hence use of read -t1 redirection is the best option. The output from the subshell can be muted with 2>&-. Here is an example from CodeMonkey's response:
mountpoint="/my/mountpoint"
read -t1 < <(stat -t "$mountpoint" 2>&-)
if [[ -n "$REPLY" ]]; then
echo "NFS mount stale. Removing..."
umount -f -l "$mountpoint"
fi
Perhaps now this question is fully answered :).
The final answers give by Ville and CodeMonkey are almost correct. I'm not sure how no one noticed this, but a $REPLY string having content is a success, not a failure. Thus, an empty $REPLY string means the mount is stale. Thus, the conditional should use -z, not -n:
mountpoint="/my/mountpoint"
read -t1 < <(stat -t "$mountpoint" 2>&-)
if [ -z "$REPLY" ] ; then
echo "NFS mount stale. Removing..."
umount -f -l "$mountpoint"
fi
I have ran this multiple times with a valid and invalid mount point and it works. The -n check gave me reverse results, echoing the mount was stale when it was absolutely valid.
Also, the double bracket isn't necessary for a simple string check.
Building off the answers here, I found some issues in testing that would output bad data due to how the $REPLY var would get updated (or not, if the result was empty), and the inconsistency of the stat command as provided in the answers.
This uses the stat command to check the FS type which responds to changes pretty fast or instant, and checks the contents of $REPLY to make sure the fs is NFS [ ref: https://unix.stackexchange.com/questions/20523/how-to-determine-what-filesystem-a-directory-exists-on ]
read -t1 < <(timeout 1 stat -f -c %T "/mnt/nfsshare/" 2>&-);if [[ ! "${REPLY}" =~ "nfs" ]];then echo "NFS mount NOT WORKING...";fi

How do I create a flag using getopts to run mount command in linux?

I need help with my script.
My script is to find if a mount exists. Though I want it run only if I pass a flag using getopts. How can I do that?
FS_TO_CHECK="/dev"
if cat /proc/mounts | grep $FS_TO_CHECK > /dev/null; then
# Filesystem is mounted
else
# Filesystem is not mounted
fi
The simplest example of passing a command line argument:
$ ./MyScript.sh some_parameter
MyScript.sh:
#!/bin/bash
echo $1
Here's a simple tutorial on getopts.

How to convert ".." in path names to absolute name in a bash script?

How to convert the .. in the path names to absolute path names in a bash script. That is, if I have a path /home/nohsib/dvc/../bop, I want this to be changed to the path without dots in it, in this case /home/nohsib/bop
How can I do that?
What you're looking for is readlink:
absolute_path=$(readlink -m /home/nohsib/dvc/../bop)
Please note: You need to use GNU's readlink implementation which offers the "-m" option. BSD's readlink for example does not.
Try:
ABSOLUTE_PATH=$(cd /home/nohsib/dvc/../bop; pwd)
One issue with using :
ABSOLUTE_PATH=$(cd ${possibleDirectory}; pwd)
is that if ${possibleDirectory} doesn't exist, ABSOLUTE_PATH will then be set to the current directory. Which is probably NOT what you want or expect.
I think using this version may be more desirable in general:
ABSOLUTE_PATH=$(cd ${possibleDirectory} && pwd)
If ${possibleDirectory} does not exist or is not accessible, due to missing directory access permissions, ABSOLUTE_PATH will contain the empty string.
The advantage of this is that you can then test for the empty string or let it fail naturally, depending on the circumstances. Defaulting to the current directory in the case of a failed 'cd' command may lead to very unexpected and possibly disastrous results (e.g. rm -rf "$ABSOLUTE_PATH" )
If you want to do it without following any symlinks, then try using realpath with option -s:
$ realpath -s /home/nohsib/dvc/../bop
/home/nohsib/bop
Note that with realpath, normally all but the last component must exist. So for the above to work, the following must all be present in the file system:
/home
/home/nohsib
/home/nohsib/dvc
But you can bypass that requirement using the -m option.
$ realpath -sm /home/nohsib/dvc/../bop
/home/nohsib/bop
(Note realpath is not available on all systems, especially older non-Debian systems. For those working on embedded Linux, unfortunately Busybox realpath doesn't support the -s or -m switches.)
Use
echo Absolute path: $(cd $1; pwd)
Just an additional note, if your current path is under a symlink, you can resolve the true path with this:
pwd -P
To solve your specific problem, this will issue a cd command to change directory to the path without the '..' in it. Note you will be in the same folder, just with the correct path:
cd `pwd -P`
As an alternative to GNU's readlink and realpath, I had created functions as well that would run in scripts independent of external commands like pwd and stuffs.
http://www.linuxquestions.org/questions/blog/konsolebox-210384/getting-absolute-paths-of-unix-directories-and-filenames-in-shell-scripts-3956/
One of those is this one. It will save the absolute path to $__. I used read there to be safe from pathname expansion.
function getabspath {
local -a T1 T2
local -i I=0
local IFS=/ A
case "$1" in
/*)
read -r -a T1 <<< "$1"
;;
*)
read -r -a T1 <<< "/$PWD/$1"
;;
esac
T2=()
for A in "${T1[#]}"; do
case "$A" in
..)
[[ I -ne 0 ]] && unset T2\[--I\]
continue
;;
.|'')
continue
;;
esac
T2[I++]=$A
done
case "$1" in
*/)
[[ I -ne 0 ]] && __="/${T2[*]}/" || __=/
;;
*)
[[ I -ne 0 ]] && __="/${T2[*]}" || __=/.
;;
esac
}
one good solution under a shell would be :
readlink -ev mypathname
It prints out the full path name with dots resolved.
Relative paths must be converted into absolute, it is NOT required to exist!
Neither symlinks should be resolved.
Try this one-line python solution:
abs_path=$(python -c "import os; print(os.path.abspath(\"$rel_path\"))")
in your example:
python -c "import os; print(os.path.abspath(\"/home/nohsib/dvc/../bop\"))"
returns /home/nohsib/bop
Try this (assuming your relative path is stored in the variable $rel_path):
echo "`cd $rel_path; pwd`"

How to get full path of a file?

Is there an easy way I can print the full path of file.txt ?
file.txt = /nfs/an/disks/jj/home/dir/file.txt
The <command>
dir> <command> file.txt
should print
/nfs/an/disks/jj/home/dir/file.txt
Use readlink:
readlink -f file.txt
I suppose you are using Linux.
I found a utility called realpath in coreutils 8.15.
realpath -s file.txt
/data/ail_data/transformed_binaries/coreutils/test_folder_realpath/file.txt
Since the question is about how to get the full/absolute path of a file and not about how to get the target of symlinks, use -s or --no-symlinks which means don't expand symlinks.
As per #styrofoam-fly and #arch-standton comments, realpath alone doesn't check for file existence, to solve this add the e argument: realpath -e file
The following usually does the trick:
echo "$(cd "$(dirname "$1")" && pwd -P)/$(basename "$1")"
I know there's an easier way that this, but darned if I can find it...
jcomeau#intrepid:~$ python -c 'import os; print(os.path.abspath("cat.wav"))'
/home/jcomeau/cat.wav
jcomeau#intrepid:~$ ls $PWD/cat.wav
/home/jcomeau/cat.wav
On Windows:
Holding Shift and right clicking on a file in Windows Explorer gives you an option called Copy as Path.
This will copy the full path of the file to clipboard.
On Linux:
You can use the command realpath yourfile to get the full path of a file as suggested by others.
find $PWD -type f | grep "filename"
or
find $PWD -type f -name "*filename*"
If you are in the same directory as the file:
ls "`pwd`/file.txt"
Replace file.txt with your target filename.
I know that this is an old question now, but just to add to the information here:
The Linux command which can be used to find the filepath of a command file, i.e.
$ which ls
/bin/ls
There are some caveats to this; please see https://www.cyberciti.biz/faq/how-do-i-find-the-path-to-a-command-file/.
You could use the fpn (full path name) script:
% pwd
/Users/adamatan/bins/scripts/fpn
% ls
LICENSE README.md fpn.py
% fpn *
/Users/adamatan/bins/scripts/fpn/LICENSE
/Users/adamatan/bins/scripts/fpn/README.md
/Users/adamatan/bins/scripts/fpn/fpn.py
fpn is not a standard Linux package, but it's a free and open github project and you could set it up in a minute.
Works on Mac, Linux, *nix:
This will give you a quoted csv of all files in the current dir:
ls | xargs -I {} echo "$(pwd -P)/{}" | xargs | sed 's/ /","/g'
The output of this can be easily copied into a python list or any similar data structure.
echo $(cd $(dirname "$1") && pwd -P)/$(basename "$1")
This is explanation of what is going on at #ZeRemz's answer:
This script get relative path as argument "$1"
Then we get dirname part of that path (you can pass either dir or file to this script): dirname "$1"
Then we cd "$(dirname "$1") into this relative dir
&& pwd -P and get absolute path for it. -P option will avoid all symlinks
After that we append basename to absolute path: $(basename "$1")
As final step we echo it
You may use this function. If the file name is given without relative path, then it is assumed to be present in the current working directory:
abspath() { old=`pwd`;new=$(dirname "$1");if [ "$new" != "." ]; then cd $new; fi;file=`pwd`/$(basename "$1");cd $old;echo $file; }
Usage:
$ abspath file.txt
/I/am/in/present/dir/file.txt
Usage with relative path:
$ abspath ../../some/dir/some-file.txt
/I/am/in/some/dir/some-file.txt
With spaces in file name:
$ abspath "../../some/dir/another file.txt"
/I/am/in/some/dir/another file.txt
You can save this in your shell.rc or just put in console
function absolute_path { echo "$PWD/$1"; }
alias ap="absolute_path"
example:
ap somefile.txt
will output
/home/user/somefile.txt
I was surprised no one mentioned located.
If you have the locate package installed, you don't even need to be in the directory with the file of interest.
Say I am looking for the full pathname of a setenv.sh script. This is how to find it.
$ locate setenv.sh
/home/davis/progs/devpost_aws_disaster_response/python/setenv.sh
/home/davis/progs/devpost_aws_disaster_response/webapp/setenv.sh
/home/davis/progs/eb_testy/setenv.sh
Note, it finds three scripts in this case, but if I wanted just one I
would do this:
$ locate *testy*setenv.sh
/home/davis/progs/eb_testy/setenv.sh
This solution uses commands that exist on Ubuntu 22.04, but generally exist on most other Linux distributions, unless they are just to hardcore for s'mores.
The shortest way to get the full path of a file on Linux or Mac is to use the ls command and the PWD environment variable.
<0.o> touch afile
<0.o> pwd
/adir
<0.o> ls $PWD/afile
/adir/afile
You can do the same thing with a directory variable of your own, say d.
<0.o> touch afile
<0.o> d=/adir
<0.o> ls $d/afile
/adir/afile
Notice that without flags ls <FILE> and echo <FILE> are equivalent (for valid names of files in the current directory), so if you're using echo for that, you can use ls instead if you want.
If the situation is reversed, so that you have the full path and want the filename, just use the basename command.
<0.o> touch afile
<0.o> basename $PWD/afile
afile
In a similar scenario, I'm launching a cshell script from some other location. For setting the correct absolute path of the script so that it runs in the designated directory only, I'm using the following code:
set script_dir = `pwd`/`dirname $0`
$0 stores the exact string how the script was executed.
For e.g. if the script was launched like this: $> ../../test/test.csh,
$script_dir will contain /home/abc/sandbox/v1/../../test
For Mac OS X, I replaced the utilities that come with the operating system and replaced them with a newer version of coreutils. This allows you to access tools like readlink -f (for absolute path to files) and realpath (absolute path to directories) on your Mac.
The Homebrew version appends a 'G' (for GNU Tools) in front of the command name -- so the equivalents become greadlink -f FILE and grealpath DIRECTORY.
Instructions for how to install the coreutils/GNU Tools on Mac OS X through Homebrew can be found in this StackExchange arcticle.
NB: The readlink -f and realpath commands should work out of the box for non-Mac Unix users.
I like many of the answers already given, but I have found this really useful, especially within a script to get the full path of a file, including following symlinks and relative references such as . and ..
dirname `readlink -e relative/path/to/file`
Which will return the full path of the file from the root path onwards.
This can be used in a script so that the script knows which path it is running from, which is useful in a repository clone which could be located anywhere on a machine.
basePath=`dirname \`readlink -e $0\``
I can then use the ${basePath} variable in my scripts to directly reference other scripts.
Hope this helps,
Dave
This worked pretty well for me. It doesn't rely on the file system (a pro/con depending on need) so it'll be fast; and, it should be portable to most any *NIX. It does assume the passed string is indeed relative to the PWD and not some other directory.
function abspath () {
echo $1 | awk '\
# Root parent directory refs to the PWD for replacement below
/^\.\.\// { sub("^", "./") } \
# Replace the symbolic PWD refs with the absolute PWD \
/^\.\// { sub("^\.", ENVIRON["PWD"])} \
# Print absolute paths \
/^\// {print} \'
}
This is naive, but I had to make it to be POSIX compliant. Requires permission to cd into the file's directory.
#!/bin/sh
if [ ${#} = 0 ]; then
echo "Error: 0 args. need 1" >&2
exit 1
fi
if [ -d ${1} ]; then
# Directory
base=$( cd ${1}; echo ${PWD##*/} )
dir=$( cd ${1}; echo ${PWD%${base}} )
if [ ${dir} = / ]; then
parentPath=${dir}
else
parentPath=${dir%/}
fi
if [ -z ${base} ] || [ -z ${parentPath} ]; then
if [ -n ${1} ]; then
fullPath=$( cd ${1}; echo ${PWD} )
else
echo "Error: unsupported scenario 1" >&2
exit 1
fi
fi
elif [ ${1%/*} = ${1} ]; then
if [ -f ./${1} ]; then
# File in current directory
base=$( echo ${1##*/} )
parentPath=$( echo ${PWD} )
else
echo "Error: unsupported scenario 2" >&2
exit 1
fi
elif [ -f ${1} ] && [ -d ${1%/*} ]; then
# File in directory
base=$( echo ${1##*/} )
parentPath=$( cd ${1%/*}; echo ${PWD} )
else
echo "Error: not file or directory" >&2
exit 1
fi
if [ ${parentPath} = / ]; then
fullPath=${fullPath:-${parentPath}${base}}
fi
fullPath=${fullPath:-${parentPath}/${base}}
if [ ! -e ${fullPath} ]; then
echo "Error: does not exist" >&2
exit 1
fi
echo ${fullPath}
This works with both Linux and Mac OSX:
echo $(pwd)$/$(ls file.txt)
find / -samefile file.txt -print
Will find all the links to the file with the same inode number as file.txt
adding a -xdev flag will avoid find to cross device boundaries ("mount points"). (But this will probably cause nothing to be found if the find does not start at a directory on the same device as file.txt)
Do note that find can report multiple paths for a single filesystem object, because an Inode can be linked by more than one directory entry, possibly even using different names. For instance:
find /bin -samefile /bin/gunzip -ls
Will output:
12845178 4 -rwxr-xr-x 2 root root 2251 feb 9 2012 /bin/uncompress
12845178 4 -rwxr-xr-x 2 root root 2251 feb 9 2012 /bin/gunzip
Usually:
find `pwd` | grep <filename>
Alternatively, just for the current folder:
find `pwd` -maxdepth 1 | grep <filename>
This will work for both file and folder:
getAbsolutePath(){
[[ -d $1 ]] && { cd "$1"; echo "$(pwd -P)"; } ||
{ cd "$(dirname "$1")" || exit 1; echo "$(pwd -P)/$(basename "$1")"; }
}
Another Linux utility, that does this job:
fname <file>
For Mac OS, if you just want to get the path of a file in the finder, control click the file, and scroll down to "Services" at the bottom. You get many choices, including "copy path" and "copy full path". Clicking on one of these puts the path on the clipboard.
fp () {
PHYS_DIR=`pwd -P`
RESULT=$PHYS_DIR/$1
echo $RESULT | pbcopy
echo $RESULT
}
Copies the text to your clipboard and displays the text on the terminal window.
:)
(I copied some of the code from another stack overflow answer but cannot find that answer anymore)
In Mac OSX, do the following steps:
cd into the directory of the target file.
Type either of the following terminal commands.
Terminal
ls "`pwd`/file.txt"
echo $(pwd)/file.txt
Replace file.txt with your actual file name.
Press Enter
you#you:~/test$ ls
file
you#you:~/test$ path="`pwd`/`ls`"
you#you:~/test$ echo $path
/home/you/test/file
Beside "readlink -f" , another commonly used command:
$find /the/long/path/but/I/can/use/TAB/to/auto/it/to/ -name myfile
/the/long/path/but/I/can/use/TAB/to/auto/it/to/myfile
$
This also give the full path and file name at console
Off-topic: This method just gives relative links, not absolute. The readlink -f command is the right one.

Resources