-1

My requirement is display output lines into mutliple lines

My code is:

#!/bin/bash
dir="$1"

echo -n "file size:"
du="$(du $dir -hab | sort -n -r | tail -1)"
printf "%s\n" "echo "$du""

It's showing output as:

     file size:echo 0
./.config/enchant/en_US.dic 

My expected output is:

file size: 0
./.config/enchant/en_US.dic 

should be displayed like above. The path should be in a new line with one tab space.

1
  • I answered this in another question, and again you have mangled the answer to produce broken code Commented May 8, 2015 at 12:40

2 Answers 2

1

The following will split the output of the pipeline using a heredoc then use the shell's builtin printf to format the text.

read -r a b <<EOF
$(du -hab "$dir" | sort -nr| tail -n 1)
EOF
printf "file size: %s\n%s\n" "$a" "$b"
1

The first issue is that you are telling printf to print the string echo followed by the value of $du. You are not telling it to print the output of the command echo "$du". To do the latter, you would need

printf "%s\n" "$(echo $du)"

That is not needed though, just tell printf to print $du:

printf "%s\n" "$du"

The next issue is that $du contains a single line like this":

file-size   path/to/file    

You will need to split that. For example, by converting tabs to newlines:

printf "%s\n" $(printf "%s\n" "$du" | tr '\t' '\n')

However, this--like your original approach--will break if your file names contain newlines. To deal with that and any other weird file name, you could do something like:

#!/usr/bin/env bash
dir="$1"

## Initialize $size to -1
size=-1;
for f in "$dir"/*; do
    ## If this is a file, set $s to its size
    [ -f "$f" ] && s=$(stat -c '%s' "$f");
    ## If this is the first file, if $size is -1, set $size to $s
    [ $size -eq -1 ] && size=$s;
    ## If the current file's size ($s) is smaller than the smallest found
    ## so far, set $name to the file's name ($f) and $size to the file's
    ## size ($s).
    [[ $s -le $size ]] && name="$f" && size="$s"
done;
## At the end, print the data
printf "file size:%s\n%s\n" "$size"  "$name"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.