Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
2  
ls has a --group-directories-first switch. –  jasonwryan Oct 18 '11 at 0:27
1  
-t is a possibly a GNU-only option to cp that takes an explicit target directory and hence can go anywhere in the command line, including the beginning. –  jw013 Oct 18 '11 at 1:23

2 Answers 2

Listing directories first for a non-GNU ls:

ls -l | sort

Note, this will list all the bunch of other weird stuff like symlinks, sockets and pipes as well (appropriately grouped, of course), but considering that stuff is quite rare that shouldn't be a problem. Otherwise the filter would be ls -l | grep '^(-|d)' | sort

share|improve this answer
    
+1 clever and shorter than the accepted answer. Except that it really should be sort -r. –  PythonNut Oct 2 at 4:42

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.

share|improve this answer
    
This is great. More generally, is there any way of knowing if I have the GNU version? (other than trying the option --group-directories-first). –  user815423426 Sep 25 '12 at 21:02
2  
You can run ls --version to find out which one you have. –  Shawn J. Goff Sep 26 '12 at 12:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.