Print name if parameter passed to function Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election Results Why I closed the “Why is Kali so hard” questionFunction to evaluate variables in BASHHow do I get the value of a named option of an already running process in Linux?Conditional execution block with || and parentheses problemShell valid function name charactersWhile loop with result from function - BASHGet specific result from functionBash function assign value to passed parameterFunction to iterate over arrayHow am I allowed to pass a void parameter through bash functions?Pass parameter to Bash function which will serve as a pattern to awk

Why didn't this character "real die" when they blew their stack out in Altered Carbon?

If a contract sometimes uses the wrong name, is it still valid?

Is it ethical to give a final exam after the professor has quit before teaching the remaining chapters of the course?

When were vectors invented?

What does this icon in iOS Stardew Valley mean?

Can an alien society believe that their star system is the universe?

Should I discuss the type of campaign with my players?

How widely used is the term Treppenwitz? Is it something that most Germans know?

Fundamental Solution of the Pell Equation

Generate an RGB colour grid

English words in a non-english sci-fi novel

How to bypass password on Windows XP account?

Why aren't air breathing engines used as small first stages

How do pianists reach extremely loud dynamics?

Is it true that "carbohydrates are of no use for the basal metabolic need"?

How discoverable are IPv6 addresses and AAAA names by potential attackers?

How to react to hostile behavior from a senior developer?

What does an IRS interview request entail when called in to verify expenses for a sole proprietor small business?

What is the logic behind the Maharil's explanation of why we don't say שעשה ניסים on Pesach?

How to find out what spells would be useless to a blind NPC spellcaster?

Why did the rest of the Eastern Bloc not invade Yugoslavia?

Why am I getting the error "non-boolean type specified in a context where a condition is expected" for this request?

Naming the result of a source block

Denied boarding although I have proper visa and documentation. To whom should I make a complaint?



Print name if parameter passed to function



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
2019 Community Moderator Election Results
Why I closed the “Why is Kali so hard” questionFunction to evaluate variables in BASHHow do I get the value of a named option of an already running process in Linux?Conditional execution block with || and parentheses problemShell valid function name charactersWhile loop with result from function - BASHGet specific result from functionBash function assign value to passed parameterFunction to iterate over arrayHow am I allowed to pass a void parameter through bash functions?Pass parameter to Bash function which will serve as a pattern to awk



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4















I have written a little function that exits if the value of the function argument is empty, I would like to be able to also print the name of the parameter (not the value!) if it is possible, my following implementation fails to print the name of the parameter.



function exitIfEmpty()

if [ -z "$1" ]
then
echo "Exiting because $!1 is empty"
exit 1
fi



when called like so



exitIfEmpty someKey



should print



Exiting because someKey is empty









share|improve this question
























  • Wait, when you give it "someKey", $1 won't be empty. If it's empty, there's nothing to print.

    – choroba
    Mar 26 at 15:08











  • @choroba I want to print the parameter name if possible not its value.

    – Xerxes
    Mar 26 at 15:09






  • 1





    What do you mean by the name? Function arguments don't have names.

    – choroba
    Mar 26 at 15:32

















4















I have written a little function that exits if the value of the function argument is empty, I would like to be able to also print the name of the parameter (not the value!) if it is possible, my following implementation fails to print the name of the parameter.



function exitIfEmpty()

if [ -z "$1" ]
then
echo "Exiting because $!1 is empty"
exit 1
fi



when called like so



exitIfEmpty someKey



should print



Exiting because someKey is empty









share|improve this question
























  • Wait, when you give it "someKey", $1 won't be empty. If it's empty, there's nothing to print.

    – choroba
    Mar 26 at 15:08











  • @choroba I want to print the parameter name if possible not its value.

    – Xerxes
    Mar 26 at 15:09






  • 1





    What do you mean by the name? Function arguments don't have names.

    – choroba
    Mar 26 at 15:32













4












4








4


1






I have written a little function that exits if the value of the function argument is empty, I would like to be able to also print the name of the parameter (not the value!) if it is possible, my following implementation fails to print the name of the parameter.



function exitIfEmpty()

if [ -z "$1" ]
then
echo "Exiting because $!1 is empty"
exit 1
fi



when called like so



exitIfEmpty someKey



should print



Exiting because someKey is empty









share|improve this question
















I have written a little function that exits if the value of the function argument is empty, I would like to be able to also print the name of the parameter (not the value!) if it is possible, my following implementation fails to print the name of the parameter.



function exitIfEmpty()

if [ -z "$1" ]
then
echo "Exiting because $!1 is empty"
exit 1
fi



when called like so



exitIfEmpty someKey



should print



Exiting because someKey is empty






bash






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 17:42









GAD3R

28.3k1958114




28.3k1958114










asked Mar 26 at 15:06









XerxesXerxes

1956




1956












  • Wait, when you give it "someKey", $1 won't be empty. If it's empty, there's nothing to print.

    – choroba
    Mar 26 at 15:08











  • @choroba I want to print the parameter name if possible not its value.

    – Xerxes
    Mar 26 at 15:09






  • 1





    What do you mean by the name? Function arguments don't have names.

    – choroba
    Mar 26 at 15:32

















  • Wait, when you give it "someKey", $1 won't be empty. If it's empty, there's nothing to print.

    – choroba
    Mar 26 at 15:08











  • @choroba I want to print the parameter name if possible not its value.

    – Xerxes
    Mar 26 at 15:09






  • 1





    What do you mean by the name? Function arguments don't have names.

    – choroba
    Mar 26 at 15:32
















Wait, when you give it "someKey", $1 won't be empty. If it's empty, there's nothing to print.

– choroba
Mar 26 at 15:08





Wait, when you give it "someKey", $1 won't be empty. If it's empty, there's nothing to print.

– choroba
Mar 26 at 15:08













@choroba I want to print the parameter name if possible not its value.

– Xerxes
Mar 26 at 15:09





@choroba I want to print the parameter name if possible not its value.

– Xerxes
Mar 26 at 15:09




1




1





What do you mean by the name? Function arguments don't have names.

– choroba
Mar 26 at 15:32





What do you mean by the name? Function arguments don't have names.

– choroba
Mar 26 at 15:32










3 Answers
3






active

oldest

votes


















13














What gets passed to the function is just a string. If you run func somevar, what is passed is the string somevar. If you run func $somevar, what is passed is (the word-split) value of the variable somevar. Neither is a variable reference, a pointer or anything like that, they're just strings.



If you want to pass the name of a variable to a function, and then look at the value of that variable, you'll need to use a nameref (Bash 4.3 or later, IIRC), or an indirect reference $!var. $!var expands to the value of the variable whose name is stored in var.



So, you just have it the wrong way in the script, if you pass the name of a variable to function, use "$!1" to get the value of the variable named in $1, and plain "$1" to get the name.



E.g. this will print variable bar is empty, exiting, and exit the shell:



#!/bin/bash
exitIfEmpty()
if [ -z "$!1" ]; then
echo "variable $1 is empty, exiting"
exit 1
fi

foo=x
unset bar
exitIfEmpty foo
exitIfEmpty bar





share|improve this answer

























  • Also: : "$!1:?Variable $1 is empty or unset".

    – Kusalananda
    Mar 27 at 10:16



















3














Pass the name as second argument



function exitIfEmpty()

if [ -z "$1" ]
then
echo "Exiting because $2 is empty"
exit 1
fi


exitIfEmpty "$someKey" someKey





share|improve this answer
































    2














    echo "Exiting because $1 is empty"


    should do the trick.






    share|improve this answer




















    • 3





      Wouldn't this always print Exiting because is empty, if the test is against $1 also? That doesn't seem very useful.

      – ilkkachu
      Mar 26 at 15:30











    • ITYM echo 'Exit because $1 is empty' or echo "Exit because $1 is empty" -- single-quote strings don't do variable expansion; double-quoted strings require $ to be escaped

      – jimbobmcgee
      Mar 26 at 19:22











    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
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f508764%2fprint-name-if-parameter-passed-to-function%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









    13














    What gets passed to the function is just a string. If you run func somevar, what is passed is the string somevar. If you run func $somevar, what is passed is (the word-split) value of the variable somevar. Neither is a variable reference, a pointer or anything like that, they're just strings.



    If you want to pass the name of a variable to a function, and then look at the value of that variable, you'll need to use a nameref (Bash 4.3 or later, IIRC), or an indirect reference $!var. $!var expands to the value of the variable whose name is stored in var.



    So, you just have it the wrong way in the script, if you pass the name of a variable to function, use "$!1" to get the value of the variable named in $1, and plain "$1" to get the name.



    E.g. this will print variable bar is empty, exiting, and exit the shell:



    #!/bin/bash
    exitIfEmpty()
    if [ -z "$!1" ]; then
    echo "variable $1 is empty, exiting"
    exit 1
    fi

    foo=x
    unset bar
    exitIfEmpty foo
    exitIfEmpty bar





    share|improve this answer

























    • Also: : "$!1:?Variable $1 is empty or unset".

      – Kusalananda
      Mar 27 at 10:16
















    13














    What gets passed to the function is just a string. If you run func somevar, what is passed is the string somevar. If you run func $somevar, what is passed is (the word-split) value of the variable somevar. Neither is a variable reference, a pointer or anything like that, they're just strings.



    If you want to pass the name of a variable to a function, and then look at the value of that variable, you'll need to use a nameref (Bash 4.3 or later, IIRC), or an indirect reference $!var. $!var expands to the value of the variable whose name is stored in var.



    So, you just have it the wrong way in the script, if you pass the name of a variable to function, use "$!1" to get the value of the variable named in $1, and plain "$1" to get the name.



    E.g. this will print variable bar is empty, exiting, and exit the shell:



    #!/bin/bash
    exitIfEmpty()
    if [ -z "$!1" ]; then
    echo "variable $1 is empty, exiting"
    exit 1
    fi

    foo=x
    unset bar
    exitIfEmpty foo
    exitIfEmpty bar





    share|improve this answer

























    • Also: : "$!1:?Variable $1 is empty or unset".

      – Kusalananda
      Mar 27 at 10:16














    13












    13








    13







    What gets passed to the function is just a string. If you run func somevar, what is passed is the string somevar. If you run func $somevar, what is passed is (the word-split) value of the variable somevar. Neither is a variable reference, a pointer or anything like that, they're just strings.



    If you want to pass the name of a variable to a function, and then look at the value of that variable, you'll need to use a nameref (Bash 4.3 or later, IIRC), or an indirect reference $!var. $!var expands to the value of the variable whose name is stored in var.



    So, you just have it the wrong way in the script, if you pass the name of a variable to function, use "$!1" to get the value of the variable named in $1, and plain "$1" to get the name.



    E.g. this will print variable bar is empty, exiting, and exit the shell:



    #!/bin/bash
    exitIfEmpty()
    if [ -z "$!1" ]; then
    echo "variable $1 is empty, exiting"
    exit 1
    fi

    foo=x
    unset bar
    exitIfEmpty foo
    exitIfEmpty bar





    share|improve this answer















    What gets passed to the function is just a string. If you run func somevar, what is passed is the string somevar. If you run func $somevar, what is passed is (the word-split) value of the variable somevar. Neither is a variable reference, a pointer or anything like that, they're just strings.



    If you want to pass the name of a variable to a function, and then look at the value of that variable, you'll need to use a nameref (Bash 4.3 or later, IIRC), or an indirect reference $!var. $!var expands to the value of the variable whose name is stored in var.



    So, you just have it the wrong way in the script, if you pass the name of a variable to function, use "$!1" to get the value of the variable named in $1, and plain "$1" to get the name.



    E.g. this will print variable bar is empty, exiting, and exit the shell:



    #!/bin/bash
    exitIfEmpty()
    if [ -z "$!1" ]; then
    echo "variable $1 is empty, exiting"
    exit 1
    fi

    foo=x
    unset bar
    exitIfEmpty foo
    exitIfEmpty bar






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 27 at 10:07

























    answered Mar 26 at 15:24









    ilkkachuilkkachu

    63.5k10104181




    63.5k10104181












    • Also: : "$!1:?Variable $1 is empty or unset".

      – Kusalananda
      Mar 27 at 10:16


















    • Also: : "$!1:?Variable $1 is empty or unset".

      – Kusalananda
      Mar 27 at 10:16

















    Also: : "$!1:?Variable $1 is empty or unset".

    – Kusalananda
    Mar 27 at 10:16






    Also: : "$!1:?Variable $1 is empty or unset".

    – Kusalananda
    Mar 27 at 10:16














    3














    Pass the name as second argument



    function exitIfEmpty()

    if [ -z "$1" ]
    then
    echo "Exiting because $2 is empty"
    exit 1
    fi


    exitIfEmpty "$someKey" someKey





    share|improve this answer





























      3














      Pass the name as second argument



      function exitIfEmpty()

      if [ -z "$1" ]
      then
      echo "Exiting because $2 is empty"
      exit 1
      fi


      exitIfEmpty "$someKey" someKey





      share|improve this answer



























        3












        3








        3







        Pass the name as second argument



        function exitIfEmpty()

        if [ -z "$1" ]
        then
        echo "Exiting because $2 is empty"
        exit 1
        fi


        exitIfEmpty "$someKey" someKey





        share|improve this answer















        Pass the name as second argument



        function exitIfEmpty()

        if [ -z "$1" ]
        then
        echo "Exiting because $2 is empty"
        exit 1
        fi


        exitIfEmpty "$someKey" someKey






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 27 at 17:30

























        answered Mar 26 at 15:18









        JShorthouseJShorthouse

        54829




        54829





















            2














            echo "Exiting because $1 is empty"


            should do the trick.






            share|improve this answer




















            • 3





              Wouldn't this always print Exiting because is empty, if the test is against $1 also? That doesn't seem very useful.

              – ilkkachu
              Mar 26 at 15:30











            • ITYM echo 'Exit because $1 is empty' or echo "Exit because $1 is empty" -- single-quote strings don't do variable expansion; double-quoted strings require $ to be escaped

              – jimbobmcgee
              Mar 26 at 19:22















            2














            echo "Exiting because $1 is empty"


            should do the trick.






            share|improve this answer




















            • 3





              Wouldn't this always print Exiting because is empty, if the test is against $1 also? That doesn't seem very useful.

              – ilkkachu
              Mar 26 at 15:30











            • ITYM echo 'Exit because $1 is empty' or echo "Exit because $1 is empty" -- single-quote strings don't do variable expansion; double-quoted strings require $ to be escaped

              – jimbobmcgee
              Mar 26 at 19:22













            2












            2








            2







            echo "Exiting because $1 is empty"


            should do the trick.






            share|improve this answer















            echo "Exiting because $1 is empty"


            should do the trick.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 14 hours ago

























            answered Mar 26 at 15:07









            PankiPanki

            872512




            872512







            • 3





              Wouldn't this always print Exiting because is empty, if the test is against $1 also? That doesn't seem very useful.

              – ilkkachu
              Mar 26 at 15:30











            • ITYM echo 'Exit because $1 is empty' or echo "Exit because $1 is empty" -- single-quote strings don't do variable expansion; double-quoted strings require $ to be escaped

              – jimbobmcgee
              Mar 26 at 19:22












            • 3





              Wouldn't this always print Exiting because is empty, if the test is against $1 also? That doesn't seem very useful.

              – ilkkachu
              Mar 26 at 15:30











            • ITYM echo 'Exit because $1 is empty' or echo "Exit because $1 is empty" -- single-quote strings don't do variable expansion; double-quoted strings require $ to be escaped

              – jimbobmcgee
              Mar 26 at 19:22







            3




            3





            Wouldn't this always print Exiting because is empty, if the test is against $1 also? That doesn't seem very useful.

            – ilkkachu
            Mar 26 at 15:30





            Wouldn't this always print Exiting because is empty, if the test is against $1 also? That doesn't seem very useful.

            – ilkkachu
            Mar 26 at 15:30













            ITYM echo 'Exit because $1 is empty' or echo "Exit because $1 is empty" -- single-quote strings don't do variable expansion; double-quoted strings require $ to be escaped

            – jimbobmcgee
            Mar 26 at 19:22





            ITYM echo 'Exit because $1 is empty' or echo "Exit because $1 is empty" -- single-quote strings don't do variable expansion; double-quoted strings require $ to be escaped

            – jimbobmcgee
            Mar 26 at 19:22

















            draft saved

            draft discarded
















































            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.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f508764%2fprint-name-if-parameter-passed-to-function%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 should I support this large drywall patch? Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?How do I cover large gaps in drywall?How do I keep drywall around a patch from crumbling?Can I glue a second layer of drywall?How to patch long strip on drywall?Large drywall patch: how to avoid bulging seams?Drywall Mesh Patch vs. Bulge? To remove or not to remove?How to fix this drywall job?Prep drywall before backsplashWhat's the best way to fix this horrible drywall patch job?Drywall patching using 3M Patch Plus Primer

            Lowndes Grove History Architecture References Navigation menu32°48′6″N 79°57′58″W / 32.80167°N 79.96611°W / 32.80167; -79.9661132°48′6″N 79°57′58″W / 32.80167°N 79.96611°W / 32.80167; -79.9661178002500"National Register Information System"Historic houses of South Carolina"Lowndes Grove""+32° 48' 6.00", −79° 57' 58.00""Lowndes Grove, Charleston County (260 St. Margaret St., Charleston)""Lowndes Grove"The Charleston ExpositionIt Happened in South Carolina"Lowndes Grove (House), Saint Margaret Street & Sixth Avenue, Charleston, Charleston County, SC(Photographs)"Plantations of the Carolina Low Countrye

            Kathakali Contents Etymology and nomenclature History Repertoire Songs and musical instruments Traditional plays Styles: Sampradayam Training centers and awards Relationship to other dance forms See also Notes References External links Navigation menueThe Illustrated Encyclopedia of Hinduism: A-MSouth Asian Folklore: An EncyclopediaRoutledge International Encyclopedia of Women: Global Women's Issues and KnowledgeKathakali Dance-drama: Where Gods and Demons Come to PlayKathakali Dance-drama: Where Gods and Demons Come to PlayKathakali Dance-drama: Where Gods and Demons Come to Play10.1353/atj.2005.0004The Illustrated Encyclopedia of Hinduism: A-MEncyclopedia of HinduismKathakali Dance-drama: Where Gods and Demons Come to PlaySonic Liturgy: Ritual and Music in Hindu Tradition"The Mirror of Gesture"Kathakali Dance-drama: Where Gods and Demons Come to Play"Kathakali"Indian Theatre: Traditions of PerformanceIndian Theatre: Traditions of PerformanceIndian Theatre: Traditions of PerformanceIndian Theatre: Traditions of PerformanceMedieval Indian Literature: An AnthologyThe Oxford Companion to Indian TheatreSouth Asian Folklore: An Encyclopedia : Afghanistan, Bangladesh, India, Nepal, Pakistan, Sri LankaThe Rise of Performance Studies: Rethinking Richard Schechner's Broad SpectrumIndian Theatre: Traditions of PerformanceModern Asian Theatre and Performance 1900-2000Critical Theory and PerformanceBetween Theater and AnthropologyKathakali603847011Indian Theatre: Traditions of PerformanceIndian Theatre: Traditions of PerformanceIndian Theatre: Traditions of PerformanceBetween Theater and AnthropologyBetween Theater and AnthropologyNambeesan Smaraka AwardsArchivedThe Cambridge Guide to TheatreRoutledge International Encyclopedia of Women: Global Women's Issues and KnowledgeThe Garland Encyclopedia of World Music: South Asia : the Indian subcontinentThe Ethos of Noh: Actors and Their Art10.2307/1145740By Means of Performance: Intercultural Studies of Theatre and Ritual10.1017/s204912550000100xReconceiving the Renaissance: A Critical ReaderPerformance TheoryListening to Theatre: The Aural Dimension of Beijing Opera10.2307/1146013Kathakali: The Art of the Non-WorldlyOn KathakaliKathakali, the dance theatreThe Kathakali Complex: Performance & StructureKathakali Dance-Drama: Where Gods and Demons Come to Play10.1093/obo/9780195399318-0071Drama and Ritual of Early Hinduism"In the Shadow of Hollywood Orientalism: Authentic East Indian Dancing"10.1080/08949460490274013Sanskrit Play Production in Ancient IndiaIndian Music: History and StructureBharata, the Nāṭyaśāstra233639306Table of Contents2238067286469807Dance In Indian Painting10.2307/32047833204783Kathakali Dance-Theatre: A Visual Narrative of Sacred Indian MimeIndian Classical Dance: The Renaissance and BeyondKathakali: an indigenous art-form of Keralaeee