Search code examples
shellcsh

Save and restore local variables in Hamilton C Shell


I try to save all the variable state at a point in a file and restore all the saved variable when needed. I don't see how to achieve the RestoreState and keeping the variable type, maybe someone has already done that ?

# script.csh
local a,b

@ a = 1
@ b = "hello"

proc SaveState ()
    local > backup.txt
endproc # SaveState

proc RestoreState ()
    # If file backup.txt exists
    if (-e backup.txt) then
        echo -- "----- Restore saved state -----"
    end # if
endproc # RestoreState

SaveState
@ b = "world"
RestoreState
# list variables, should print 1 and "hello"
local

Edit: "1" == 1 so it is not necessary to keep variable type


Solution

  • I found a solution by using sed and by saving the backup.txt file in a format that can be read by the source command:

    proc SaveState ()
        local | sed 's/^^\([a-zA-Z0-9_]*\)[\t ]*\(.*\)$/@ \1 = "\2"/' > backup.txt
    endproc # SaveState
    
    proc RestoreState ()
        # If file backup.txt exists
        if (-e backup.txt) then
            source backup.txt
        end # if
    endproc # RestoreState