This is one of those things that comes from lots of experience. You were on the right track by looking at echo
and printf
.
I'm going to start by using command substitution, because it's the first method that comes to mind. I'll combine it with echo
. (It's that experience thing again.) You can read up about command substitution in lots of places, try Googling it or check out the question and answers here.
Our goal can be stated as performing these steps:
#Not real code
$ echo "<number_of_files> <number_of_directories>"
Command substitution simply allows us to use the output of a command to give us <number_of_files>
and <number_of_directories>
. To get these outputs, we use the pattern $(my_command)
, which will give whatever output that running
$ my_command
at the terminal gives. Hopefully this will become clearer when you get to the part I've marked by putting the words, "Here we do the command substitution", in bold.
I'm going to imagine that you've got a directory structure something like what follows. (I call it no_stack_dir
because you don't want your numbers stacked one on top of the other.)
no_stack_dir/
├── dir1
├── dir2
├── file1
├── file2
├── file3
└── file4
I'm going to simplify things by not creating a script. Instead of using "$1"
, I'm just going to use a directory name -- in this case /home/jsmith147/no_stack_dir
. Before I show the method, I hope to ensure that our directory setup is understood by using the following commands.
$ cd ~
$ pwd
/home/jsmith147
$ls
no_stack_dir
$ls no_stack_dir
dir1 file2
dir2 file3
file1 file4
Notice I have only 2 subdirectories, because our find
command will include no_stack_dir
in its found directories along with dir1
and dir2
.
Here we do the command substition, combined with echo
.
Our <number_of_files>
comes from the command,
find /home/jsmith147/no_stack_dir -type f | wc -l
and our <number_of_directories>
comes from the command,
find /home/jsmith147/no_stack_dir -type d | wc -l
Note that I didn't put the terminal prompt, $
before those commands. Here is where command substitution comes in. We go from
#Not real code
$ echo "<number_of_files> <number_of_directories>"
to
#Real code
$ echo "$(find /home/jsmith147/no_stack_dir -type f | wc -l) $(find /home/jsmith147/no_stack_dir -type d | wc -l)"
I hope I've made it clear enough with these examples so that you can write a script (or something else that uses "$1"
) that would be run something like
$ ./no_stack.sh /home/jsmith147/no_stack_dir
Feel free to ask questions. There are many other ways to accomplish what you are trying to do. Perhaps the SO community can come up with a bunch of other ways to produce the same output. It would be interesting to list them here.