How to store command with option on variable of a function in zsh?

I’m trying to learn bash scripting using freeCodeCamp tutorial for beginners on YouTube.

I’m stuck at the point where he shows how to create a function.
He saved on a variable a command with an option


    up=$(uptime -p | cut -c4-)
    since=$(uptime -s)
    cat << EOF

This machine has been up for ${up}
It has been running since ${since}



I’m not able to replicate on my MacBook M1 with zsh on terminal.

I’m using #!/bin/zsh
and It works only if I don’t pass the -p and -s options.


uptime: illegal option -- p
usage: uptime
uptime: illegal option -- s
usage: uptime

To clear a few things up:

  • As variable of a function you would rather indicate the arguments passed to the function (none here) which are accessed via $1, $2, and so on.
  • What you have are variables in your functions and because they are not marked local they are not even limited to the function.
  • The $( ) construct is called command substitution. It does not store the command in any way but instead executes what is inside it (uptime -p | cut -c4- in your first case) and assigns the output the command produced to the variable. The uptime command is executed at this point. The command output is stored, not the command.
  • As Marcus mentioned the error comes from the uptime command not supporting those options. Since Mac OS is related to BSD the FreeBSD man page for uptime can give an orientation. On FreeBSD uptime accepts no options at all and it is probably the same for Mac OS.
  • To answer the question title: the best way to store a command with options is to use an array. my_stored_command=(ls -lt --human-readable /home) can then later be run as "${my_stored_command[@]}" which expands the array to its individual elements again forming a command invocation.
Answered By: Paul Pazderski
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.