How do I check if a symbolic link exists in Linux (Ubuntu/RHEL/CentOS/Docker/Bash)

Let me explain, how to test a soft-link or a symbolic link that exist in bash, this works across all Linux OS types, (Ubuntu, CentOS, Docker Linux containers, and shell scripts)

Lets start with a simple commandline test, using the test command

test -L my-soft-link

If this directory doesnt exist, so here is the expected output:

dev@codetryout:/var/tmp$ test -L my-soft-link
dev@codetryout:/var/tmp$ 
dev@codetryout:/var/tmp$ echo $?
1
dev@codetryout:/var/tmp$

Now, we are going to create a soft link and test it again

dev@codetryout:/var/tmp$ mkdir test
dev@codetryout:/var/tmp$ 
dev@codetryout:/var/tmp$ ln -s test my-soft-link
dev@codetryout:/var/tmp$ 
dev@codetryout:/var/tmp$ test -L my-soft-link
dev@codetryout:/var/tmp$ 
dev@codetryout:/var/tmp$ echo $?
0
dev@codetryout:/var/tmp$ 

Note, the $? variable is used to check the status of the last command executed.

  • 0 if the last command was successful
  • 1 if it was unsuccessful