5

I need to add items to a list of items. I am not sure if these are the correct terms.

Example:

Suppose I am inside a directory with 2 files, "a" and "b". If I pipe ls to less my list will have two items, "a" and "b": ls | less

I want to pipe ls to less, but before reach the less command I want an item added to the list. e.g:

ls -->unknow shell feature<-- less

And the content listed by less would be "a", "b" and "c" (file "c" doesn't exist)

Is it possible?

2
  • I understand your question up to the point where you mention c. What is c?
    – Kusalananda
    Sep 19 at 6:13
  • @Kusalananda "c" is just a string to be appended to the list.
    – Lawrence
    Sep 19 at 11:55

3 Answers 3

10

The simplest would be

(ls;echo c) | less

1
  • 3
    You can save a subprocess with { ls; echo c; } | less Sep 19 at 19:09
5

Yes, it's possible to achieve that. Here are two examples:

Using pipes twice:

ls | (cat;echo fuzz) | less

Using input redirection:

ls | less < <(cat;echo fuzz)

In zsh shells you can also use:

ls | <<<"buzz" | less
#or
ls | < <(echo fuzz) | less
2

If all you want is to list each visible name in the current directory, add c to the end of the list, and view the result in less:

printf '%s\n' * c | less

The rest of this answer deals with creating a separate list of filenames, adding something to that list and then either using it as arguments to less, or viewing the list in less (depending on how we interpret the question).


You may use an array to store the names of all visible files in the current directory:

names=( * )

You may add things to the end of an array:

names+=( c )

... or in one go when you set the array's initial values:

names=( * c )

You may use the elements in the array as arguments to less:

less -- "${names[@]}"

(The -- is used to ensure that less interprets the arguments as filenames and not as options. This matters if any filename starts with a dash.)

Or, you may list the elements of the names array using less:

printf '%s\n' "${names[@]}" | less

Doing the same things but using the list of positional parameters in place of a named array:

set -- *
set -- "$@" c

... or,

set -- * c

Then calling less with these elements as arguments:

less -- "$@"

Or, listing the positional parameters with less:

printf '%s\n' "$@" | less

Note that the quoting in all the above commands is important. Quoting "$@" and "${names[@]}" like this ensures that the shell expands them as lists of individually quoted elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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