Search code examples
pythonshelljupyter-notebookgoogle-colaboratory

Concatenate command string in a shell script in Google Colab or Jupyter in general


Suppose we have a string variable in python and we want to concatenate it with other string in the shell script. For example, suppose the variable is a base address. We want to run a command, rm for example, over a file in the base directory, like the following:

base_address = "<addr>"
!echo "${base_address}/file_name.xml"

But it doesn't work, here (in contrast to the bash). It's the same story for "$base_address/file_name.xml". What is the solution?


Solution

  • To contact a string variable in the shell script, you need to put it besides the other part of the string like the following:

    base_address = "<addr>"
    !echo $base_address"/file_name.xml"
    

    Moreover, if you have a variable for the file name you can do it quite similar:

    base_address = "<addr>/"
    file_name = "file_name.xml"
    !echo $base_address$file_name
    

    Note that this would be useful in Jupyter notebooks as well.