MSYR
MSYR

Reputation: 95

No such file error in bash script to list files

I'm trying to write a bash script that lists all the files in a directory. Here's my code:

#!/bin/bash

FOLDER_NAME=$1

if ! [ -d "$FOLDER_NAME" ]; then
    echo "Error: Folder does not exist!" 
    exit 0 
fi

FILE_NAMES=$("ls ${FOLDER_NAME}/*")

echo $FILE_NAMES

When i run my script with any directory (lets say .) the output shows

ls ./*: No such file or directory

But when I run that ls command in my shell in lists all the files correctly. I'm fairly new to bash. I don't understand what's wrong in the code.

Upvotes: 1

Views: 718

Answers (1)

Francesco
Francesco

Reputation: 977

The problem is the way you use double quotes in FILE_NAMES=$("ls ${FOLDER_NAME}/*"). Note 1: using "$1" instead of $1 will help you when you will face folders with spaces in their name; Note 2: exit status 0 means success in Linux, you should use an other number instead. Try this:

#!/bin/bash

FOLDER_NAME="$1"

if ! [ -d "$FOLDER_NAME" ]; then
    echo "Error: Folder does not exist!" 
    exit 1 
fi

FILE_NAMES=$(ls "$FOLDER_NAME"/*)

echo $FILE_NAMES

Upvotes: 2

Related Questions