Shell – How to list files and directories with directories first

command linelsshell-script

I have two questions. First, which command lists files and directories, but lists directories first?

Second question: I want to copy a list of files into a single directory, but make the target directory the first filename in the command.

Best Answer

Got GNU?

The gnu version of ls has --group-directories-first. And cp has -t.

No GNU?

On systems that don't have gnu's ls, your best bet is two successive calls to find with -maxdepth n/-mindepth n and -type t with the appropriate options.

find . -maxdepth 1 -mindepth 1 -type d
find . -maxdepth 1 -mindepth 1 \! -type d

For copying files, with the target first, you would have to write a script that saves the first argument, then uses shift, and appends the argument to the end.

#!/bin/sh
target="$1"
shift
cp -r -- "$@" "$target"

Watch Out!

If you were planning on using these together - that is, collecting the list from find or ls (possibly by using xargs) and passing it to cp (or a cp wrapper), you should be aware of what dangers lie in parsing lists of files (basically, filenames can contain characters like newlines that can mess up your script). Specifically, look into find's -exec and -print0 options and xargs's -0 option.

An alternative tool for efficiently copying directory trees.

You might want to look into using rsync instead; it has lots of functionality that might make your job easier.

Related Question