0

I want to write a program which will check if soft links exist or not

#!/bin/bash
file="/var/link1"
if [[ -L "$file" ]]; then
    echo "$file symlink is present";
    exit 0
else
    echo "$file symlink is not present";
    exit 1
fi

There will be link2, link3, link4, link5.

Do I have to write the same script n number of times for n number of links or can this be achieved in one script?

Also I want to have the exit 0 and exit 1 so that I can use for monitoring purpose.

alamoot
  • 1,966
  • 7
  • 30
  • 50
  • You want to return 0 or 1 depending on whether the link exists, but also want handle multiple links. I don't see how you can have both features. You probably need to modify your script to accept a command line argument for `file` so that you can reuse it. https://stackoverflow.com/q/192249/397817 – Stephen Kennedy Feb 18 '18 at 16:37
  • 1
    Instead of writing the script n times, use a `for` loop to go over the links – alamoot Feb 18 '18 at 17:01
  • This seems very, very much like an XY problem -- you're asking how to do X (store multiple values in a variable), but what you *really* want is to do Y (reuse some code with different values). – Charles Duffy Feb 18 '18 at 19:46
  • It's also notable that anything much more complicated than `for link in /var/link{1,2,3,4,5}; do [[ -L "$link" ]] || exit; done` is almost certainly more complicated than it needs to be. (`exit` exits with `$?` by default, so `[[ -L non-existing-file ]] || exit` exits with status 1; similarly, the implicit exit at the end of a script likewise uses `$?`, so the implicit exit from a script whose last command did not fail will always have exit status 0). – Charles Duffy Feb 18 '18 at 21:15

1 Answers1

1

You can use a function:

checklink() {
   if [[ -L "$1" ]]; then
      echo "$1 symlink is present";
      return 0
   else
      echo "$1 symlink is not present";
      return 1
   fi
}

file1="/var/link1"
file2="/var/link2"
file3="/var/link3"
file4="/var/link4"

for f in "${file1}" "${file2}" "${file3}" "${file4}"; do
   checklink "$f" || { echo "Exit in view of missing link"; exit 1; }
done
echo "All symlinks checked"
exit 0
Walter A
  • 19,067
  • 2
  • 23
  • 43
  • `{echo` is not `{ echo`. And there's a reference to `$file` in the function that needs to be changed to `$1`. – Charles Duffy Feb 18 '18 at 19:48
  • It can be achieved by the below as well #!/bin/bash file=$1 if [[ -L "$file" ]]; then echo "$file symlink is present"; exit 0 else echo "$file symlink is not present"; exit 1 fi And call this script as test.sh /usr/bin/ls test.sh /bin/find – Premkumar Waghmare Feb 19 '18 at 17:38