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.

4
  • 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. stackoverflow.com/q/192249/397817 Commented Feb 18, 2018 at 16:37
  • 1
    Instead of writing the script n times, use a for loop to go over the links Commented Feb 18, 2018 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). Commented Feb 18, 2018 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). Commented Feb 18, 2018 at 21:15

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

{echo is not { echo. And there's a reference to $file in the function that needs to be changed to $1.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.