0

I am having a problem with the condition of the second if statement [ -z "$(ls -A $workdir)" ] if the workdir path has space in it. I tried to enclose it with "$workdir" but not working. I appreciate your help.

#!/bin/bash

workdir=${1:-$(pwd)}

if [ -d "$workdir" ]; then
    if [ -z "$(ls -A $workdir)" ]; then
        echo "Working directory is set to: $workdir"
    else
        echo "Working directory is not empty!"
        read -p "Do you want to continue? (y/n) " choice
        if [[ "$choice" == [yY] ]]; then
            echo "Continuing..."
        elif [[ "$choice" == [nN] ]]; then
            echo "Exiting."
            exit 0
        else
            echo "Invalid choice. Please enter y or n."
            exit 1
        fi
    fi
else
    echo "Creating and setting as working directory: $workdir"
    mkdir -p "$workdir"
fi

mkdir -p "${workdir}"/{code,data,docs,logs,outs,temp}
mkdir -p "${workdir}/code/utils"
mkdir -p "${workdir}/data/{raw,processed}"

I need a way to include paths that have empty strings in the above code without raising errors.

MKali
  • 11
  • 2
  • 1
    The following page contains hints why it is not useful to use the output of `ls`: [Why *not* parse `ls`?](http://unix.stackexchange.com/questions/128985/why-not-parse-ls) – Cyrus Apr 04 '23 at 07:31
  • You simply want to check if `"$workdir"/*` expands to existing files or not. See the duplicate for a more elaborate exposition. – tripleee Apr 04 '23 at 08:10
  • Using double-quotes, like `if [ -z "$(ls -A "$workdir")" ]` *should* work. If it doesn't, how exactly does it fail and under what circumstances (i.e. directory empty, full, both, etc)? Also, in the final line, `{raw,processed}` needs to be outside the double-quotes in order to expand. – Gordon Davisson Apr 04 '23 at 08:11
  • _I tried to enclose it with "$workdir" but not working_ : What do you mean by _not working_? While double quotes in general can't be nested, they can in this case, due to the `$(...)` in between. I just wonder what exactly you want to achieve. – user1934428 Apr 04 '23 at 08:51
  • when i mean it did not work i.e. if workdir is a path with empty space like "~/my folder" it parse "~/my" and "folder" separately – MKali Apr 06 '23 at 04:53

1 Answers1

-2
if [ -z `ls -A "$workdir"` ]; then
balu
  • 1
  • 2