AJJ
AJJ

Reputation: 2074

Including newlines in ls output?

Practicing some Bash scripting:

  1 #!/bin/bash
  2 
  3 read -p "Input the path to a file or directory: " TARGET_PATH
  4 
  5 if [ -f "${TARGET_PATH}" ]
  6 then
  7     echo "${TARGET_PATH} is a file!"
  8     echo $(ls ${TARGET_PATH} -l)
  9 elif [ -d "${TARGET_PATH}" ]
 10 then
 11     echo "${TARGET_PATH} is a directory!"
 12     echo $(ls ${TARGET_PATH} -l)
 13 else
 14     echo "${TARGET_PATH} is not a file or directory."
 15 fi

This works as intended if TARGET_PATH is a file, the ls -l command runs against it fine enough.

But if it's a directory, the output of ls -l squishes many items into one line.

I tried iterating over the ls -l command in that instance but it split everything by spaces so every single piece ended up on a new line.

Is there a way to output the contents similar to what we'd expect it to do had we entered ls -l at the terminal?

Upvotes: 0

Views: 1960

Answers (1)

David Z
David Z

Reputation: 131550

Using the -1 option (that's a number one, not a lowercase L) to ls will make it output one item per line.

ls -1l "${TARGET_PATH}"

Upvotes: 3

Related Questions