Defining and using a variable in batch file

前端 未结 4 1534
一向
一向 2020-11-22 16:01

I\'m trying to define and use a variable in a batch file. It looks like it should be simple:

@echo off

set locatio         


        
相关标签:
4条回答
  • 2020-11-22 16:29

    input location.bat

    @echo off
    cls
    
    set /p "location"="bob"
    echo We're working with %location%
    pause
    

    output

    We're working with bob
    

    (mistakes u done : space and " ")

    0 讨论(0)
  • 2020-11-22 16:41

    Consider also using SETX - it will set variable on user or machine (available for all users) level though the variable will be usable with the next opening of the cmd.exe ,so often it can be used together with SET :

    ::setting variable for the current user
    if not defined My_Var (
      set "My_Var=My_Value"
      setx My_Var My_Value
    )
    
    ::setting machine defined variable
    if not defined Global_Var (
      set "Global_Var=Global_Value"
      SetX Global_Var Global_Value /m
    )
    

    You can also edit directly the registry values:

    User Variables: HKEY_CURRENT_USER\Environment

    System Variables: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

    Which will allow to avoid some restrictions of SET and SETX like the variables containing = in their names.

    0 讨论(0)
  • 2020-11-22 16:42

    The space before the = is interpreted as part of the name, and the space after it (as well as the quotation marks) are interpreted as part of the value. So the variable you’ve created can be referenced with %location %. If that’s not what you want, remove the extra space(s) in the definition.

    0 讨论(0)
  • 2020-11-22 16:43

    The spaces are significant. You created a variable named 'location ' with a value of
    ' "bob"'. Note - enclosing single quotes were added to show location of space.

    If you want quotes in your value, then your code should look like

    set location="bob"
    

    If you don't want quotes, then your code should look like

    set location=bob
    

    Or better yet

    set "location=bob"
    

    The last syntax prevents inadvertent trailing spaces from getting in the value, and also protects against special characters like & | etc.

    0 讨论(0)
提交回复
热议问题