How to create an environment variable that is the output of a command












3














How do I create an environment variable that is the result of a specific command?
Specifically, I want an environment variable ($BWD) that is the basename of $PWD



$ cd /home/devel/Autils/lib
$ echo $PWD
/home/devel/Autils/lib
$ # something here to assign BWD
$ echo $BWD
lib









share|improve this question









New contributor




Josh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

























    3














    How do I create an environment variable that is the result of a specific command?
    Specifically, I want an environment variable ($BWD) that is the basename of $PWD



    $ cd /home/devel/Autils/lib
    $ echo $PWD
    /home/devel/Autils/lib
    $ # something here to assign BWD
    $ echo $BWD
    lib









    share|improve this question









    New contributor




    Josh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.























      3












      3








      3







      How do I create an environment variable that is the result of a specific command?
      Specifically, I want an environment variable ($BWD) that is the basename of $PWD



      $ cd /home/devel/Autils/lib
      $ echo $PWD
      /home/devel/Autils/lib
      $ # something here to assign BWD
      $ echo $BWD
      lib









      share|improve this question









      New contributor




      Josh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      How do I create an environment variable that is the result of a specific command?
      Specifically, I want an environment variable ($BWD) that is the basename of $PWD



      $ cd /home/devel/Autils/lib
      $ echo $PWD
      /home/devel/Autils/lib
      $ # something here to assign BWD
      $ echo $BWD
      lib






      environment-variables alias






      share|improve this question









      New contributor




      Josh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      Josh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited yesterday









      Jeff Schaller

      39k1054125




      39k1054125






      New contributor




      Josh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked yesterday









      JoshJosh

      212




      212




      New contributor




      Josh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Josh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Josh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          3 Answers
          3






          active

          oldest

          votes


















          9














          In general the sequence foo="$(bar)" will run the command bar and assign the output to the variable.



          e.g.



          % echo $PWD
          /home/sweh
          % BWD="$(basename "$PWD")"
          % echo $BWD
          sweh


          This creates a shell variable. If you want to make it into an environment variable (which can be seen by sub-shells) you can export it.



          e.g.



          export BWD="$(basename "$PWD")"


          However, in this case don't need to run a command, but use shell variable expansion



          BWD=${PWD##*/}





          share|improve this answer



















          • 1




            The next step would be to automatically update BWD when cd is used: cd () { builtin cd "$@" && BWD=${PWD##*/}; }.
            – Kusalananda
            yesterday










          • @Kusalananda trap 'BWD=${PWD##*/}' DEBUG :-)
            – Stephen Harris
            yesterday










          • Depending on the shell used, yes.
            – Kusalananda
            yesterday










          • I'd add quotes to the echo commands as well.
            – kasperd
            17 hours ago



















          12














          In Bourne-like shells, you create environment variables by marking a shell variable with the export attribute (so it's exported to the environment of the commands that the shell will execute) by using the export builtin utility:



          export BWD


          To assign a value to a shell variable, the syntax is:



          BWD=value


          You can make that value the output of command by using command substitution. In the Bourne shell, that was with the `the-command` syntax, but in modern Bourne-like shells, the preferred way is with $(the-command) instead:



          BWD=$(the-command)


          Usually, you need quotes around command substitutions to prevent split+glob. However, split+glob doesn't occur in assignments to scalar variables, so they're not necessary here.



          The command to get the base name of a file path is the basename command.



          basename "$PWD"


          (the quotes there are necessary as split+glob does occur in arguments to commands).



          That would return the base name of the file stored in $PWD, unless that value starts with -, in which case, YMMV as many basename implementations will treat it as an option. So generally, when passing variable data to command, we use a -- to tell the command that what's after is not to be taken as an option even if it starts with - (here, $PWD should always start with / except in very pathological cases, so it's not strictly needed).



          BWD=$(basename -- "$PWD")
          export BWD


          In modern shells, you can combine both with:



          export BWD="$(basename -- "$PWD")"


          (the quotes are needed in some implementations as we're back in the arguments of commands, though some other implementations do parse the arguments of export like assignments as a special case under some conditions).



          One problem with that approach is if the value of $PWD ends in newline characters (unlikely in practice) as command substitution strips all trailing newline characters. So in:



          mkdir $'foonn'
          cd $'foonn'
          export BWD="$(basename -- "$PWD")"


          $BWD will contain foo instead of $'foonn'.



          Instead, you may want to use shell builtin operators to get that base name. In zsh, that can be done with $PWD:t (t for tail); in all POSIX-like shells (including zsh), that can be done with ${PWD##*/} which removes everything up to the right-most / from the content of $PWD.



          It will give a different result however if $PWD is /. In that case, basename returns / but ${PWD##*/} or $PWD:t expand to the empty string instead. For a directory like /foo/bar/ ($PWD usually doesn't end in / though except for / itself), basename and $PWD:t give bar, while ${PWD##*/} give the empty string again.



          For a variable that dynamically expands to the basename of $PWD, you may use ksh93 and its discipline function:



          ksh93 also has a builtin version of basename provided you have /opt/ast/bin ahead of $PATH. So in ksh93:



          $ PATH=/opt/ast/bin:$PATH
          $ type basename
          basename is a shell builtin version of /opt/ast/bin/basename
          $ BWD.get() { .sh.value=${ basename -- "$PWD"; }; }
          $ cd /var/log
          $ echo "$BWD"
          log
          $ cd /usr/local
          $ echo "$BWD"
          local
          $ export BWD
          $ printenv BWD
          local


          Above, we're using a ksh93-specific form of command substitution: ${ the-command; } which is more efficient in that it doesn't create a subshell environment to run the command.






          share|improve this answer































            3














            You can use the construct foo="$(command)" to return the output of command into the variable foo. So, for your use-case:



            $ BWD="$(basename "$PWD")"





            share|improve this answer



















            • 2




              Or BWD=${PWD##*/}
              – jasonwryan
              yesterday










            • True, but does not answer the underlying actual question asked (to wit: how to assign the output of a command into a variable).
              – DopeGhoti
              yesterday












            • eh? What do you think BWD is? The fact that OP assumes it requires a command does not make it necessary, just misguided.
              – jasonwryan
              yesterday










            • Again, this specific use-case does in fact not require a command, but the question explicitly asked was "how do I get the output of a command into a variable".
              – DopeGhoti
              yesterday










            • OP also explicitly says: "Specifically, I want an environment variable ($BWD) that is the basename of $PWD" Don't selectively quote just because you assume it supports your argument, that is bad faith. OP wanted an outcome, and like many posters, assumed there was only one route there.
              – jasonwryan
              yesterday













            Your Answer








            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "106"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });






            Josh is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f493081%2fhow-to-create-an-environment-variable-that-is-the-output-of-a-command%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            9














            In general the sequence foo="$(bar)" will run the command bar and assign the output to the variable.



            e.g.



            % echo $PWD
            /home/sweh
            % BWD="$(basename "$PWD")"
            % echo $BWD
            sweh


            This creates a shell variable. If you want to make it into an environment variable (which can be seen by sub-shells) you can export it.



            e.g.



            export BWD="$(basename "$PWD")"


            However, in this case don't need to run a command, but use shell variable expansion



            BWD=${PWD##*/}





            share|improve this answer



















            • 1




              The next step would be to automatically update BWD when cd is used: cd () { builtin cd "$@" && BWD=${PWD##*/}; }.
              – Kusalananda
              yesterday










            • @Kusalananda trap 'BWD=${PWD##*/}' DEBUG :-)
              – Stephen Harris
              yesterday










            • Depending on the shell used, yes.
              – Kusalananda
              yesterday










            • I'd add quotes to the echo commands as well.
              – kasperd
              17 hours ago
















            9














            In general the sequence foo="$(bar)" will run the command bar and assign the output to the variable.



            e.g.



            % echo $PWD
            /home/sweh
            % BWD="$(basename "$PWD")"
            % echo $BWD
            sweh


            This creates a shell variable. If you want to make it into an environment variable (which can be seen by sub-shells) you can export it.



            e.g.



            export BWD="$(basename "$PWD")"


            However, in this case don't need to run a command, but use shell variable expansion



            BWD=${PWD##*/}





            share|improve this answer



















            • 1




              The next step would be to automatically update BWD when cd is used: cd () { builtin cd "$@" && BWD=${PWD##*/}; }.
              – Kusalananda
              yesterday










            • @Kusalananda trap 'BWD=${PWD##*/}' DEBUG :-)
              – Stephen Harris
              yesterday










            • Depending on the shell used, yes.
              – Kusalananda
              yesterday










            • I'd add quotes to the echo commands as well.
              – kasperd
              17 hours ago














            9












            9








            9






            In general the sequence foo="$(bar)" will run the command bar and assign the output to the variable.



            e.g.



            % echo $PWD
            /home/sweh
            % BWD="$(basename "$PWD")"
            % echo $BWD
            sweh


            This creates a shell variable. If you want to make it into an environment variable (which can be seen by sub-shells) you can export it.



            e.g.



            export BWD="$(basename "$PWD")"


            However, in this case don't need to run a command, but use shell variable expansion



            BWD=${PWD##*/}





            share|improve this answer














            In general the sequence foo="$(bar)" will run the command bar and assign the output to the variable.



            e.g.



            % echo $PWD
            /home/sweh
            % BWD="$(basename "$PWD")"
            % echo $BWD
            sweh


            This creates a shell variable. If you want to make it into an environment variable (which can be seen by sub-shells) you can export it.



            e.g.



            export BWD="$(basename "$PWD")"


            However, in this case don't need to run a command, but use shell variable expansion



            BWD=${PWD##*/}






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited yesterday









            DopeGhoti

            43.6k55382




            43.6k55382










            answered yesterday









            Stephen HarrisStephen Harris

            25.3k24477




            25.3k24477








            • 1




              The next step would be to automatically update BWD when cd is used: cd () { builtin cd "$@" && BWD=${PWD##*/}; }.
              – Kusalananda
              yesterday










            • @Kusalananda trap 'BWD=${PWD##*/}' DEBUG :-)
              – Stephen Harris
              yesterday










            • Depending on the shell used, yes.
              – Kusalananda
              yesterday










            • I'd add quotes to the echo commands as well.
              – kasperd
              17 hours ago














            • 1




              The next step would be to automatically update BWD when cd is used: cd () { builtin cd "$@" && BWD=${PWD##*/}; }.
              – Kusalananda
              yesterday










            • @Kusalananda trap 'BWD=${PWD##*/}' DEBUG :-)
              – Stephen Harris
              yesterday










            • Depending on the shell used, yes.
              – Kusalananda
              yesterday










            • I'd add quotes to the echo commands as well.
              – kasperd
              17 hours ago








            1




            1




            The next step would be to automatically update BWD when cd is used: cd () { builtin cd "$@" && BWD=${PWD##*/}; }.
            – Kusalananda
            yesterday




            The next step would be to automatically update BWD when cd is used: cd () { builtin cd "$@" && BWD=${PWD##*/}; }.
            – Kusalananda
            yesterday












            @Kusalananda trap 'BWD=${PWD##*/}' DEBUG :-)
            – Stephen Harris
            yesterday




            @Kusalananda trap 'BWD=${PWD##*/}' DEBUG :-)
            – Stephen Harris
            yesterday












            Depending on the shell used, yes.
            – Kusalananda
            yesterday




            Depending on the shell used, yes.
            – Kusalananda
            yesterday












            I'd add quotes to the echo commands as well.
            – kasperd
            17 hours ago




            I'd add quotes to the echo commands as well.
            – kasperd
            17 hours ago













            12














            In Bourne-like shells, you create environment variables by marking a shell variable with the export attribute (so it's exported to the environment of the commands that the shell will execute) by using the export builtin utility:



            export BWD


            To assign a value to a shell variable, the syntax is:



            BWD=value


            You can make that value the output of command by using command substitution. In the Bourne shell, that was with the `the-command` syntax, but in modern Bourne-like shells, the preferred way is with $(the-command) instead:



            BWD=$(the-command)


            Usually, you need quotes around command substitutions to prevent split+glob. However, split+glob doesn't occur in assignments to scalar variables, so they're not necessary here.



            The command to get the base name of a file path is the basename command.



            basename "$PWD"


            (the quotes there are necessary as split+glob does occur in arguments to commands).



            That would return the base name of the file stored in $PWD, unless that value starts with -, in which case, YMMV as many basename implementations will treat it as an option. So generally, when passing variable data to command, we use a -- to tell the command that what's after is not to be taken as an option even if it starts with - (here, $PWD should always start with / except in very pathological cases, so it's not strictly needed).



            BWD=$(basename -- "$PWD")
            export BWD


            In modern shells, you can combine both with:



            export BWD="$(basename -- "$PWD")"


            (the quotes are needed in some implementations as we're back in the arguments of commands, though some other implementations do parse the arguments of export like assignments as a special case under some conditions).



            One problem with that approach is if the value of $PWD ends in newline characters (unlikely in practice) as command substitution strips all trailing newline characters. So in:



            mkdir $'foonn'
            cd $'foonn'
            export BWD="$(basename -- "$PWD")"


            $BWD will contain foo instead of $'foonn'.



            Instead, you may want to use shell builtin operators to get that base name. In zsh, that can be done with $PWD:t (t for tail); in all POSIX-like shells (including zsh), that can be done with ${PWD##*/} which removes everything up to the right-most / from the content of $PWD.



            It will give a different result however if $PWD is /. In that case, basename returns / but ${PWD##*/} or $PWD:t expand to the empty string instead. For a directory like /foo/bar/ ($PWD usually doesn't end in / though except for / itself), basename and $PWD:t give bar, while ${PWD##*/} give the empty string again.



            For a variable that dynamically expands to the basename of $PWD, you may use ksh93 and its discipline function:



            ksh93 also has a builtin version of basename provided you have /opt/ast/bin ahead of $PATH. So in ksh93:



            $ PATH=/opt/ast/bin:$PATH
            $ type basename
            basename is a shell builtin version of /opt/ast/bin/basename
            $ BWD.get() { .sh.value=${ basename -- "$PWD"; }; }
            $ cd /var/log
            $ echo "$BWD"
            log
            $ cd /usr/local
            $ echo "$BWD"
            local
            $ export BWD
            $ printenv BWD
            local


            Above, we're using a ksh93-specific form of command substitution: ${ the-command; } which is more efficient in that it doesn't create a subshell environment to run the command.






            share|improve this answer




























              12














              In Bourne-like shells, you create environment variables by marking a shell variable with the export attribute (so it's exported to the environment of the commands that the shell will execute) by using the export builtin utility:



              export BWD


              To assign a value to a shell variable, the syntax is:



              BWD=value


              You can make that value the output of command by using command substitution. In the Bourne shell, that was with the `the-command` syntax, but in modern Bourne-like shells, the preferred way is with $(the-command) instead:



              BWD=$(the-command)


              Usually, you need quotes around command substitutions to prevent split+glob. However, split+glob doesn't occur in assignments to scalar variables, so they're not necessary here.



              The command to get the base name of a file path is the basename command.



              basename "$PWD"


              (the quotes there are necessary as split+glob does occur in arguments to commands).



              That would return the base name of the file stored in $PWD, unless that value starts with -, in which case, YMMV as many basename implementations will treat it as an option. So generally, when passing variable data to command, we use a -- to tell the command that what's after is not to be taken as an option even if it starts with - (here, $PWD should always start with / except in very pathological cases, so it's not strictly needed).



              BWD=$(basename -- "$PWD")
              export BWD


              In modern shells, you can combine both with:



              export BWD="$(basename -- "$PWD")"


              (the quotes are needed in some implementations as we're back in the arguments of commands, though some other implementations do parse the arguments of export like assignments as a special case under some conditions).



              One problem with that approach is if the value of $PWD ends in newline characters (unlikely in practice) as command substitution strips all trailing newline characters. So in:



              mkdir $'foonn'
              cd $'foonn'
              export BWD="$(basename -- "$PWD")"


              $BWD will contain foo instead of $'foonn'.



              Instead, you may want to use shell builtin operators to get that base name. In zsh, that can be done with $PWD:t (t for tail); in all POSIX-like shells (including zsh), that can be done with ${PWD##*/} which removes everything up to the right-most / from the content of $PWD.



              It will give a different result however if $PWD is /. In that case, basename returns / but ${PWD##*/} or $PWD:t expand to the empty string instead. For a directory like /foo/bar/ ($PWD usually doesn't end in / though except for / itself), basename and $PWD:t give bar, while ${PWD##*/} give the empty string again.



              For a variable that dynamically expands to the basename of $PWD, you may use ksh93 and its discipline function:



              ksh93 also has a builtin version of basename provided you have /opt/ast/bin ahead of $PATH. So in ksh93:



              $ PATH=/opt/ast/bin:$PATH
              $ type basename
              basename is a shell builtin version of /opt/ast/bin/basename
              $ BWD.get() { .sh.value=${ basename -- "$PWD"; }; }
              $ cd /var/log
              $ echo "$BWD"
              log
              $ cd /usr/local
              $ echo "$BWD"
              local
              $ export BWD
              $ printenv BWD
              local


              Above, we're using a ksh93-specific form of command substitution: ${ the-command; } which is more efficient in that it doesn't create a subshell environment to run the command.






              share|improve this answer


























                12












                12








                12






                In Bourne-like shells, you create environment variables by marking a shell variable with the export attribute (so it's exported to the environment of the commands that the shell will execute) by using the export builtin utility:



                export BWD


                To assign a value to a shell variable, the syntax is:



                BWD=value


                You can make that value the output of command by using command substitution. In the Bourne shell, that was with the `the-command` syntax, but in modern Bourne-like shells, the preferred way is with $(the-command) instead:



                BWD=$(the-command)


                Usually, you need quotes around command substitutions to prevent split+glob. However, split+glob doesn't occur in assignments to scalar variables, so they're not necessary here.



                The command to get the base name of a file path is the basename command.



                basename "$PWD"


                (the quotes there are necessary as split+glob does occur in arguments to commands).



                That would return the base name of the file stored in $PWD, unless that value starts with -, in which case, YMMV as many basename implementations will treat it as an option. So generally, when passing variable data to command, we use a -- to tell the command that what's after is not to be taken as an option even if it starts with - (here, $PWD should always start with / except in very pathological cases, so it's not strictly needed).



                BWD=$(basename -- "$PWD")
                export BWD


                In modern shells, you can combine both with:



                export BWD="$(basename -- "$PWD")"


                (the quotes are needed in some implementations as we're back in the arguments of commands, though some other implementations do parse the arguments of export like assignments as a special case under some conditions).



                One problem with that approach is if the value of $PWD ends in newline characters (unlikely in practice) as command substitution strips all trailing newline characters. So in:



                mkdir $'foonn'
                cd $'foonn'
                export BWD="$(basename -- "$PWD")"


                $BWD will contain foo instead of $'foonn'.



                Instead, you may want to use shell builtin operators to get that base name. In zsh, that can be done with $PWD:t (t for tail); in all POSIX-like shells (including zsh), that can be done with ${PWD##*/} which removes everything up to the right-most / from the content of $PWD.



                It will give a different result however if $PWD is /. In that case, basename returns / but ${PWD##*/} or $PWD:t expand to the empty string instead. For a directory like /foo/bar/ ($PWD usually doesn't end in / though except for / itself), basename and $PWD:t give bar, while ${PWD##*/} give the empty string again.



                For a variable that dynamically expands to the basename of $PWD, you may use ksh93 and its discipline function:



                ksh93 also has a builtin version of basename provided you have /opt/ast/bin ahead of $PATH. So in ksh93:



                $ PATH=/opt/ast/bin:$PATH
                $ type basename
                basename is a shell builtin version of /opt/ast/bin/basename
                $ BWD.get() { .sh.value=${ basename -- "$PWD"; }; }
                $ cd /var/log
                $ echo "$BWD"
                log
                $ cd /usr/local
                $ echo "$BWD"
                local
                $ export BWD
                $ printenv BWD
                local


                Above, we're using a ksh93-specific form of command substitution: ${ the-command; } which is more efficient in that it doesn't create a subshell environment to run the command.






                share|improve this answer














                In Bourne-like shells, you create environment variables by marking a shell variable with the export attribute (so it's exported to the environment of the commands that the shell will execute) by using the export builtin utility:



                export BWD


                To assign a value to a shell variable, the syntax is:



                BWD=value


                You can make that value the output of command by using command substitution. In the Bourne shell, that was with the `the-command` syntax, but in modern Bourne-like shells, the preferred way is with $(the-command) instead:



                BWD=$(the-command)


                Usually, you need quotes around command substitutions to prevent split+glob. However, split+glob doesn't occur in assignments to scalar variables, so they're not necessary here.



                The command to get the base name of a file path is the basename command.



                basename "$PWD"


                (the quotes there are necessary as split+glob does occur in arguments to commands).



                That would return the base name of the file stored in $PWD, unless that value starts with -, in which case, YMMV as many basename implementations will treat it as an option. So generally, when passing variable data to command, we use a -- to tell the command that what's after is not to be taken as an option even if it starts with - (here, $PWD should always start with / except in very pathological cases, so it's not strictly needed).



                BWD=$(basename -- "$PWD")
                export BWD


                In modern shells, you can combine both with:



                export BWD="$(basename -- "$PWD")"


                (the quotes are needed in some implementations as we're back in the arguments of commands, though some other implementations do parse the arguments of export like assignments as a special case under some conditions).



                One problem with that approach is if the value of $PWD ends in newline characters (unlikely in practice) as command substitution strips all trailing newline characters. So in:



                mkdir $'foonn'
                cd $'foonn'
                export BWD="$(basename -- "$PWD")"


                $BWD will contain foo instead of $'foonn'.



                Instead, you may want to use shell builtin operators to get that base name. In zsh, that can be done with $PWD:t (t for tail); in all POSIX-like shells (including zsh), that can be done with ${PWD##*/} which removes everything up to the right-most / from the content of $PWD.



                It will give a different result however if $PWD is /. In that case, basename returns / but ${PWD##*/} or $PWD:t expand to the empty string instead. For a directory like /foo/bar/ ($PWD usually doesn't end in / though except for / itself), basename and $PWD:t give bar, while ${PWD##*/} give the empty string again.



                For a variable that dynamically expands to the basename of $PWD, you may use ksh93 and its discipline function:



                ksh93 also has a builtin version of basename provided you have /opt/ast/bin ahead of $PATH. So in ksh93:



                $ PATH=/opt/ast/bin:$PATH
                $ type basename
                basename is a shell builtin version of /opt/ast/bin/basename
                $ BWD.get() { .sh.value=${ basename -- "$PWD"; }; }
                $ cd /var/log
                $ echo "$BWD"
                log
                $ cd /usr/local
                $ echo "$BWD"
                local
                $ export BWD
                $ printenv BWD
                local


                Above, we're using a ksh93-specific form of command substitution: ${ the-command; } which is more efficient in that it doesn't create a subshell environment to run the command.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited yesterday

























                answered yesterday









                Stéphane ChazelasStéphane Chazelas

                300k54564916




                300k54564916























                    3














                    You can use the construct foo="$(command)" to return the output of command into the variable foo. So, for your use-case:



                    $ BWD="$(basename "$PWD")"





                    share|improve this answer



















                    • 2




                      Or BWD=${PWD##*/}
                      – jasonwryan
                      yesterday










                    • True, but does not answer the underlying actual question asked (to wit: how to assign the output of a command into a variable).
                      – DopeGhoti
                      yesterday












                    • eh? What do you think BWD is? The fact that OP assumes it requires a command does not make it necessary, just misguided.
                      – jasonwryan
                      yesterday










                    • Again, this specific use-case does in fact not require a command, but the question explicitly asked was "how do I get the output of a command into a variable".
                      – DopeGhoti
                      yesterday










                    • OP also explicitly says: "Specifically, I want an environment variable ($BWD) that is the basename of $PWD" Don't selectively quote just because you assume it supports your argument, that is bad faith. OP wanted an outcome, and like many posters, assumed there was only one route there.
                      – jasonwryan
                      yesterday


















                    3














                    You can use the construct foo="$(command)" to return the output of command into the variable foo. So, for your use-case:



                    $ BWD="$(basename "$PWD")"





                    share|improve this answer



















                    • 2




                      Or BWD=${PWD##*/}
                      – jasonwryan
                      yesterday










                    • True, but does not answer the underlying actual question asked (to wit: how to assign the output of a command into a variable).
                      – DopeGhoti
                      yesterday












                    • eh? What do you think BWD is? The fact that OP assumes it requires a command does not make it necessary, just misguided.
                      – jasonwryan
                      yesterday










                    • Again, this specific use-case does in fact not require a command, but the question explicitly asked was "how do I get the output of a command into a variable".
                      – DopeGhoti
                      yesterday










                    • OP also explicitly says: "Specifically, I want an environment variable ($BWD) that is the basename of $PWD" Don't selectively quote just because you assume it supports your argument, that is bad faith. OP wanted an outcome, and like many posters, assumed there was only one route there.
                      – jasonwryan
                      yesterday
















                    3












                    3








                    3






                    You can use the construct foo="$(command)" to return the output of command into the variable foo. So, for your use-case:



                    $ BWD="$(basename "$PWD")"





                    share|improve this answer














                    You can use the construct foo="$(command)" to return the output of command into the variable foo. So, for your use-case:



                    $ BWD="$(basename "$PWD")"






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited yesterday

























                    answered yesterday









                    DopeGhotiDopeGhoti

                    43.6k55382




                    43.6k55382








                    • 2




                      Or BWD=${PWD##*/}
                      – jasonwryan
                      yesterday










                    • True, but does not answer the underlying actual question asked (to wit: how to assign the output of a command into a variable).
                      – DopeGhoti
                      yesterday












                    • eh? What do you think BWD is? The fact that OP assumes it requires a command does not make it necessary, just misguided.
                      – jasonwryan
                      yesterday










                    • Again, this specific use-case does in fact not require a command, but the question explicitly asked was "how do I get the output of a command into a variable".
                      – DopeGhoti
                      yesterday










                    • OP also explicitly says: "Specifically, I want an environment variable ($BWD) that is the basename of $PWD" Don't selectively quote just because you assume it supports your argument, that is bad faith. OP wanted an outcome, and like many posters, assumed there was only one route there.
                      – jasonwryan
                      yesterday
















                    • 2




                      Or BWD=${PWD##*/}
                      – jasonwryan
                      yesterday










                    • True, but does not answer the underlying actual question asked (to wit: how to assign the output of a command into a variable).
                      – DopeGhoti
                      yesterday












                    • eh? What do you think BWD is? The fact that OP assumes it requires a command does not make it necessary, just misguided.
                      – jasonwryan
                      yesterday










                    • Again, this specific use-case does in fact not require a command, but the question explicitly asked was "how do I get the output of a command into a variable".
                      – DopeGhoti
                      yesterday










                    • OP also explicitly says: "Specifically, I want an environment variable ($BWD) that is the basename of $PWD" Don't selectively quote just because you assume it supports your argument, that is bad faith. OP wanted an outcome, and like many posters, assumed there was only one route there.
                      – jasonwryan
                      yesterday










                    2




                    2




                    Or BWD=${PWD##*/}
                    – jasonwryan
                    yesterday




                    Or BWD=${PWD##*/}
                    – jasonwryan
                    yesterday












                    True, but does not answer the underlying actual question asked (to wit: how to assign the output of a command into a variable).
                    – DopeGhoti
                    yesterday






                    True, but does not answer the underlying actual question asked (to wit: how to assign the output of a command into a variable).
                    – DopeGhoti
                    yesterday














                    eh? What do you think BWD is? The fact that OP assumes it requires a command does not make it necessary, just misguided.
                    – jasonwryan
                    yesterday




                    eh? What do you think BWD is? The fact that OP assumes it requires a command does not make it necessary, just misguided.
                    – jasonwryan
                    yesterday












                    Again, this specific use-case does in fact not require a command, but the question explicitly asked was "how do I get the output of a command into a variable".
                    – DopeGhoti
                    yesterday




                    Again, this specific use-case does in fact not require a command, but the question explicitly asked was "how do I get the output of a command into a variable".
                    – DopeGhoti
                    yesterday












                    OP also explicitly says: "Specifically, I want an environment variable ($BWD) that is the basename of $PWD" Don't selectively quote just because you assume it supports your argument, that is bad faith. OP wanted an outcome, and like many posters, assumed there was only one route there.
                    – jasonwryan
                    yesterday






                    OP also explicitly says: "Specifically, I want an environment variable ($BWD) that is the basename of $PWD" Don't selectively quote just because you assume it supports your argument, that is bad faith. OP wanted an outcome, and like many posters, assumed there was only one route there.
                    – jasonwryan
                    yesterday












                    Josh is a new contributor. Be nice, and check out our Code of Conduct.










                    draft saved

                    draft discarded


















                    Josh is a new contributor. Be nice, and check out our Code of Conduct.













                    Josh is a new contributor. Be nice, and check out our Code of Conduct.












                    Josh is a new contributor. Be nice, and check out our Code of Conduct.
















                    Thanks for contributing an answer to Unix & Linux Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f493081%2fhow-to-create-an-environment-variable-that-is-the-output-of-a-command%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to make a Squid Proxy server?

                    Is this a new Fibonacci Identity?

                    19世紀