Bash: ls subfield behavior

I am wondering why I am not getting the same output:

ls -1 -tF | head -n 1

and

echo $(ls -1 -tF | head -n 1)

I tried to get the last modified file, but using it inside subclasses, sometimes I get more than one file as a result?

Why is this and how to avoid?

+4
source share
2 answers

The problem arises because you are using an undefined subshell and the flag -Ffor ls displays special shell characters added to the file names.

-F, --classify
            add an indicator (one of * / => @ |) to the entry

Executable files are added using *.

At startup

echo $(ls -1 -tF | head -n 1)

then

$(ls -1 -tF | head -n 1)

will return the file name, and if it is an executable file, and there will also be a prefix for another file, it will return both.

,

test.sh
test.sh.backup

test.sh*

-

test.sh test.sh.backup

echo "$(ls -1 -tF | head -n 1)"

test.sh*
+6

: echo $(ls -1 -tF | head -n 1) globing .

, echo "$(ls -1 -tF | head -n 1)" .

, , * .

-F , :

.bashrc, :

function L {
  myvar=$1; h=${myvar:="1"};
  echo "last ${h} modified file(s):"; 
  export L=$(ls -1 -tF|fgrep -v / |head -n ${h}| sed 's/\(\*\|=\|@\)$//g' );    
  ls -l $L;
}
function LD {
  myvar=$1;
  h=${myvar:="1"};
  echo "last ${h} modified directories:"; 
  export LD=$(ls -1 -tF|fgrep / |head -n $h | sed 's/\(\*\|=\|@\)$//g'); ls -ld $LD;
}
alias ol='L; xdg-open $L'
alias cdl='LD; cd $LD'

, L ( L 5) ( 5) . .

L; jmacs $L , . lt = 'ls -lrt', ...

mkdir... cdl .

0

Source: https://habr.com/ru/post/1688223/


All Articles